How do I add cssnano optimization rules in vue-cli 3?

2.3k Views Asked by At

I am trying to add cssnano optimization rules but with vue-cli, it doesn't seem to work. I added the following script in vue.config.js:

module.exports = {
  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          require("cssnano")({
            preset: [
              "default",
              {
                discardComments: {
                  removeAll: true
                },
                mergeRules: true
              }
            ]
          })
        ]
      }
    }
  }
};

But it wouldn't work (see screenshot below)

Screenshot - cssnano mergeRules didn't apply:

enter image description here

What did I miss?

1

There are 1 best solutions below

0
On

You have to modify chainWebpack api to edit cssnano plugin options.

Run these commands:

npx vue-cli-service inspect --mode=production --plugins 

This gives you a list of plugins included in our webpack config. One of them is called 'optimize-css'

npx vue-cli-service inspect --mode=production --plugin optimize-css

Now you get the config for that plugin, including the cssnano config. You also get info in the comments about how to navigate to it through webpack-chain.

With that information, we can now use the chainWebpack api to edit the plugin options:

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.plugin('optimize-css').tap(([options]) => {
      options.cssnanoOptions.preset[1].svgo = false
      return [options]
    })
  }
}

Untested, so no guarantees :wink:

Source: https://forum.vuejs.org/t/vue-cli-3-remove-svgo-from-cssnano-optimizations/53560/2