Search code examples
javascriptwebpackpostcsscssnano

Cssnano doesn't remove duplicates


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.


Solution

  • 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.