cssnano-webpack-plugin
This plugin uses cssnano to optimize and minify your CSS.
Fully integrated in Webpack ecosystem: based on compiler hooks, respecting default Webpack output sources and compatible with other plugins like SourceMapDevToolPlugin or webpack-subresource-integrity.
Just like optimize-css-assets-webpack-plugin but more accurate with source maps and assets using query string.
Works with Webpack 4+.
Getting Started
First, install cssnano-webpack-plugin
:
$ npm install cssnano-webpack-plugin --save-dev
Then add the plugin to your webpack
configuration. For example:
webpack.config.js
const CssnanoPlugin = ; moduleexports = module: loaders: test: /.s?css$/ use: MiniCssExtractPluginloader 'css-loader' 'sass-loader' optimization: minimizer: ;
This will enable CSS optimization only in production mode. If you want to run it also in development, put the plugin configuration in the plugins
option array.
Options
test
Type: String|RegExp|Array<String|RegExp>
- default: /\.css(\?.*)?$/i
Test to match files against.
moduleexports = optimization: minimizer: test: /\.foo\.css$/i ;
include
and exclude
options are also supported (see module rules).
sourceMap
Type: Boolean|Object
- default: false
Enable (and configure) source map support. Use PostCss SourceMap options. Default configuration when enabled: { inline: false }
.
moduleexports = optimization: minimizer: sourceMap: true ;
cssnanoOptions
Type: Object
- default: { preset: 'default' }
Cssnano optimisations options.
moduleexports = optimization: minimizer: cssnanoOptions: preset: 'default' discardComments: removeAll: true ;
Examples
Use sourcemaps
Don't forget to enable sourceMap
options for all loaders.
const CssnanoPlugin = ; moduleexports = module: loaders: test: /.s?css$/ use: MiniCssExtractPluginloader loader: 'css-loader' options: sourceMap: true loader: 'sass-loader' options: sourceMap: true optimization: minimizer: sourceMap: true ;
Remove all comments
Remove all comments (including comments starting with /*!
).
moduleexports = optimization: minimizer: cssnanoOptions: preset: 'default' discardComments: removeAll: true ;