31
votes

I am having problem minimizing the css file output by the extract-text-webpack-plugin

/* webpack.config.js */
...
loader: [{test: /\.css$/, loader: ExtractTextPlugin.extract('css?minimize')}]
...
plugins: [new ExtractTextPlugin("styles.css")]
...

/* test.js */
require('./file1.css')
/* file1.css */
@import './file2.css';
body {color: green;}
body {font-size: 1rem;}

/* file2.css */
body {border: 1px solid;}
body {background: purple;}

/* the output styles.css */
body{color:green;font-size:1rem}body{border:1px solid;background:purple}

In the resulting styles.css, there are 2 body tags. It seems that minifications are performed within a file (within file1.css and within file2.css) but not when the two files are combined and extracted into the final styles.css.

How can minification be performed on the final style.css? So the output is

body{color:green;font-size:1rem;border:1px solid;background:purple}
3

3 Answers

48
votes

You could use optimize-css-assets-webpack-plugin, which was created to solve this exact issue.

plugins: [
    new ExtractTextPlugin("styles.css"),
    new OptimizeCssAssetsPlugin()
]
2
votes

For css minification you may use the webpack's CSS-loader with the "minimize" option. It solved the problem in my case:

webpack.config.js

...
module: {
   rules: [
      {
         test: /\.css$/,
         use: [{
            loader: "css-loader",
            options: {
               minimize: true
            }
         }
      },
   ]
},
...
0
votes

Paul's answer has stopped working with breaking change in 1.0.0 Minimize and some other options has been removed from options.

The recommended solution is to use optimize-cssnano-plugin. This plugin works better with source maps than optimize-css-assets-webpack-plugin.

Example:

plugins: [
    new ExtractTextPlugin("styles.css"),
    new OptimizeCssnanoPlugin({
        sourceMap: nextSourceMap,
        cssnanoOptions: {
        preset: ['default', {
            discardComments: {
            removeAll: true,
            },
        }],
        },
    }),
]