2

I have a React web application where i use CSS modules. I am using Webpack to build the application.

Related part from the webpack.config.js :

  {
    test: /\.css$/,
    use: extractCSS.extract(
    {
      fallback: 'style-loader',
      use: [{
          loader: 'css-loader',
          options: {
            modules: true,
            importLoaders: 1,
            localIdentName: '[name]__[local]___[hash:base64:5]',
          },
        },
        {
          loader: 'postcss-loader',
          options: {
            ident: 'postcss',
            plugins: () => [
              require('autoprefixer')({}),
              require('postcss-discard-empty')({}),
              require('postcss-discard-comments')({}),
              require('postcss-color-function')({}),
              require('postcss-flexbugs-fixes')({}),
              require('cssnano')({
                preset: ['default', {
                  discardComments: {
                    removeAll: true,
                  },
                  colormin: false,
                  cssDeclarationSorter: false,
                }],
              }),
            ],
          },
        },
      ],
    }),
  },

The minification seems to work. I could find some duplicate CSS rules present in the CSS like below

CSS

I am wondering whether this is a problem with my configuration or the tools I am using (PostCss and CssNano)

Thanks you.

Shanaka Rusith
  • 421
  • 1
  • 4
  • 19

1 Answers1

4

It happens because you have CSS minifier (cssnano) is postcss-loader. Loaders are applied to every file separated, as result cssnano doesn’t see other files to remove duplicates across files.

Use mini-css-extract-plugin. This plugin use cssnano as well. But it calls cssnano after concatenating every file to one big bundle. As result, cssnano will see all CSS together and will be able to remove duplicates across the whole bundle.

Andrey Sitnik
  • 971
  • 6
  • 9
  • You might want to run cssnano in "advanced" mode, while at it. This provides better optimization, but be warned - it might break css in some cases. See https://cssnano.co/guides/advanced-transforms for mor info and http://goalsmashers.github.io/css-minification-benchmark/ for advanced vs. default vs. other css optimizers. – marko-36 Apr 27 '20 at 12:30
  • 2
    Wrong. mini-css-extract-plugin doesn't even have cssnano in dependencies. The plugin you need is [optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin). – crabvk Jun 13 '20 at 12:50