20

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?

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
Hamed
  • 1,351
  • 9
  • 23
  • 3
    the best solution is stopping using unused CSS – smnbbrv Apr 04 '18 at 17:38
  • 3
    I'm loading some internal branding CSS file similar to bootstrap. But most of the time, many parts are unused. So I need a way to omit redundant parts. – Hamed Apr 04 '18 at 18:53
  • 1
    There is already a beta version for extract text plugin that works with webpack 4. Maybe thats an option if you don't find something else. https://github.com/webpack-contrib/extract-text-webpack-plugin/releases/tag/v4.0.0-beta.0 – lukas-reineke Apr 06 '18 at 10:01
  • @Hamed were you able to figure this out? – Jazzy Jan 02 '19 at 23:28
  • 6
    Try the purge-css-webpack-plugin - https://github.com/FullHuman/purgecss-webpack-plugin - This shrunk my css files considerably and is easy to implement. – bilcker Nov 07 '19 at 16:25
  • 1
    @bilcker they forked it to: https://github.com/FullHuman/purgecss – Picard Jun 25 '20 at 22:20

1 Answers1

2

Have you considered using something called uncss. There's a webpack plugin for it. It will look through all your CSS and compare it to your HTML, and remove anything that you're not using.

Take a look: WebPack UnCSS

Millhorn
  • 2,953
  • 7
  • 39
  • 77