如何通过CSS模块的Webpack 4摇树删除未使用的类?

时间:2019-01-02 23:27:45

标签: reactjs webpack css-loader css-modules

有人根据是否使用JS模块做了great example来删除未使用的CSS,但是我试图弄清楚如何从捆绑中删除那些组件未实际使用的未使用的CSS类。

示例

// Sub.scss
.sub-container {
  background-color: green;
}

.unused-junk {
  color: blue;
}


// Sub.js
import React from "react";

import styles from "./Sub.scss";

export default function Sub() {
  return <div className={styles.subContainer}>Hi from sub.</div>;
}


// App.scss
.app-container {
  background-color: red;
}


// App.js
import React from "react";
import ReactDOM from "react-dom";

import Sub from "./Sub";
import styles from "./App.scss";

function App() {
  return (
    <div className={styles.appContainer}>
      Hi from app.
      <Sub />
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

// webpack.config.js
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");

module.exports = {
  entry: "./src/App.js",
  output: {
    path: __dirname + "/build",
    filename: "bundle.js"
  },
  module: {
    rules: [
      {
        test: /\.js/,
        loader: "babel-loader",
        include: __dirname + "/src",
        query: {
          presets: ["react"]
        }
      },
      {
        test: /\.scss/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: "css-loader",
            options: {
              modules: true,
              camelCase: true,
              importLoaders: 1,
              localIdentName: "[name]--[local]--[hash:base64:5]"
            }
          },
          "sass-loader"
        ],
        include: __dirname + "/src"
      }
    ]
  },
  plugins: [
    new CopyWebpackPlugin([{ from: `src/index.html`, to: "index.html" }]),
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css"
    })
  ]
};


// CSS bundle
.App--app-container--3wd6W {
  background-color: red; }

.Sub--sub-container--38uqh {
  background-color: green; }

.Sub--unused-junk--2-h5r {
  color: blue; }

有没有办法从捆绑包中摇晃.unused-junk类?

0 个答案:

没有答案