How to remove unused CSS using webpack 4?

2020-08-09 11:31发布

问题:

I am having problem removing unused CSS in webpack 4. It seems that most of the CSS purification plugins are dependent on extract text plugin which is not updated for version 4.

Here's my commands:

node_modules/.bin/webpack --mode=development --env.operation=separateCSS

OR

node_modules/.bin/webpack --mode=development --env.operation=bundleCSS

Here's part of my webpack.config.js:

rules: [
    // Loader for SASS files
    {
      test: /\.s[ac]ss$/,
      use: [
        // Use IIFE to choose how to emit the CSS: 1. Extract as separate file 2: Bundle with the JS file
        (() => {
          return env.operation == "separateCSS" ? MiniCssExtractPlugin.loader : 'style-loader';
        })(),
        {
          loader: 'css-loader',
          options: {
            importLoaders: 1,
            url: true
          }
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: [
              // Write future-proof CSS and forget old preprocessor specific syntax. 
              // Use the latest CSS syntax today with cssnext. 
              // It transforms CSS specs into more compatible CSS so you don’t need to wait for browser support.
              // It parses CSS and add vendor prefixes to CSS rules using values from Can I Use.
              // https://github.com/MoOx/postcss-cssnext
              require('postcss-cssnext')()
            ]
          }
        },
        'sass-loader'
      ]
    }
  ],
  plugins: [
    new MiniCssExtractPlugin({
      filename: "../css/[name].css"
    })
  ]

Does anybody know how can I modify my config file so webpack can remove unused CSS?