Green
Green

Reputation: 5000

Webpack extract-text-webpack-plugin and css-loader minification

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}

Upvotes: 31

Views: 10006

Answers (3)

Black
Black

Reputation: 10397

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,
            },
        }],
        },
    }),
]

Upvotes: 0

Paul Basenko
Paul Basenko

Reputation: 1015

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
            }
         }
      },
   ]
},
...

Upvotes: 2

Alexandre Kirszenberg
Alexandre Kirszenberg

Reputation: 36408

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

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

Upvotes: 48

Related Questions