How to remove unused CSS using webpack 4?
Asked Answered
I

1

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?

Inessive answered 4/4, 2018 at 17:27 Comment(6)
the best solution is stopping using unused CSSHagerman
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.Inessive
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. github.com/webpack-contrib/extract-text-webpack-plugin/releases/…Neuritis
@Inessive were you able to figure this out?Bullyboy
Try the purge-css-webpack-plugin - github.com/FullHuman/purgecss-webpack-plugin - This shrunk my css files considerably and is easy to implement.Raynata
@Raynata they forked it to: github.com/FullHuman/purgecssSinusoid
L
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

Leah answered 10/11, 2020 at 23:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.