Configuration

You can configure cssnano either in the PostCSS configuration or in a dedicated cssnano configuration. The PostCSS configuration takes precedence over the dedicated cssnano configuration. Without configuration, cssnano runs with the default preset.

Configuration files

Configure through the PostCSS configuration

In the PostCSS configuration, you can pass both the preset and plugins options when you add cssnano to the PostCSS plugins. For example, if you use PostCSS programmatically, the following uses cssnano with the lite preset and adds the autoprefixer plugin.

import postcss from 'postcss';
import cssnano from 'cssnano';
import litePreset from 'cssnano-preset-lite';
import autoprefixer from 'autoprefixer';
const preset = litePreset({ discardComments: false });

postcss([cssnano({ preset, plugins: [autoprefixer] })])
  .process("/* Your CSS here */");

Configure through a dedicated cssnano configuration

You can configure cssnano with a dedicated configuration, for example if you cannot access the PostCSS configuration file. The cssnano configuration can be in different formats:

Configuration options

Choose a preset

Pass a preset to choose a pre-configured set of optimizations. You can specify a preset with the preset name as a string or by passing the result of importing the preset package.

With the preset as import:

cssnano({ preset: require('cssnano-preset-default') })

Using a string is useful if you use a configuration file in the JSON format.

cssnano({ preset: 'cssnano-preset-default' })

When you use a string, if the preset is called cssnano-preset-<name>, you can use name alone:

cssnano({ preset: 'default' })

Disable a plugin included in a preset

You can disable one or more of the plugins used in a preset. Pass an array where the first element is the preset and the second is an object with the preset options.

// cssnano.config.js
module.exports = {
  preset: [ 
    require('cssnano-preset-default'),
    { discardComments: false } 
  ]
};

You can also pass preset options when you use the preset name as a string: For example, here's how to deactivate the discardComments plugin when using the advanced preset:

cssnano({ 
  preset: [
    'cssnano-preset-advanced', { discardComments: false }
  ]
});

Use individual plugins

You can also pass a list of plugins to cssnano. To configure the individual plugins, use an array of arrays:

cssnano({ plugins: [['autoprefixer', {}]] });

Last updated on Wed, 05 Jun 2024 10:27:34 GMT