使用PurgeCSS,TailwindCSS和Webpack

时间:2018-07-30 23:23:03

标签: javascript css webpack purge tailwind-css

我正在尝试为使用TailwindCSS构建的静态站点设置Webpack。我正在尝试使用PurgeCSS来制作我的css文件,并清除所有未使用的东西,但我认为它没有用。它将编译没有错误,但css文件为16kb,并且Google灯塔审核说有未使用的css。

webpack.config.js

    const path = require("path");
    const glob = require("glob-all");
    const ExtractTextPlugin = require("extract-text-webpack-plugin");
    const PurgecssPlugin = require("purgecss-webpack-plugin");

    /**
     * Custom PurgeCSS Extractor
     * https://github.com/FullHuman/purgecss
     * https://github.com/FullHuman/purgecss-webpack-plugin
     */
    class TailwindExtractor {
      static extract(content) {
        return content.match(/[A-z0-9-:\/]+/g);
      }
    }

    module.exports = {
      entry: "./index.js",
      output: {
        path: path.resolve(__dirname, "dist"),
        filename: "styles.css"
      },
      module: {
        rules: [
          {
            test: /\.css$/,
            use: ExtractTextPlugin.extract({
              fallback: "style-loader",
              use: [{ loader: "css-loader", options: { importLoaders: 1 } }, "postcss-loader"]
            })
          }
        ]
      },
      plugins: [
        new ExtractTextPlugin("styles.css"),
        new PurgecssPlugin({
          paths: glob.sync([
            path.join(__dirname, "src/styles.css"),
            path.join(__dirname, "index.html")
          ]),
          extractors: [
            {
              extractor: TailwindExtractor,
              extensions: ["html", "js"]
            }
          ]
        })
      ]
    };

package.json

{
    "private": true,
    "scripts": {
        "dev": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=webpack.config.js",
        "prod": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=webpack.config.js"
    },
    "devDependencies": {
        "ajv": "^6.5.2",
        "cross-env": "^5.1",
        "css-loader": "^0.28.7",
        "extract-text-webpack-plugin": "^3.0.2",
        "postcss": "^6.0.14",
        "postcss-loader": "^2.0.8",
        "purgecss-webpack-plugin": "^1.2.0",
        "style-loader": "^0.19.0",
        "tailwindcss": "^0.6.4",
        "webpack": "^3.8.1"
    },
    "dependencies": {
        "glob-all": "^3.1.0"
    }
}

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

您是否要使用npm buildyarn build编译代码?

如果转到“使用Tailwind处理CSS”下的TailwindCSS文档,则有“使用Tailwind与PostCSS一起使用”部分,并且链接有模板存储库,您可以在其中查看如何完成此操作。 我首先看到的是您的入口点是index.js,在模板仓库中它是./src/styles.css

答案 1 :(得分:0)

如果您编译的CSS仅为16Kb,那么PurgeCSS肯定可以正常工作,如果没有它,Tailwind将输出〜300Kb。