Can not minify the css code with webpack

Alexander Loginov picture Alexander Loginov · Aug 9, 2018 · Viewed 21.1k times · Source

Webpack version: 4.16.3

All compilation is successful.
My code after compilation in bundle.css is not minify.
I try to use minimize: true in text-webpack-plugin, but it not working.

For compile I use command in command line: webpack in my working directory

What am I doing wrong?

My wepback config:

'use strict'

const webpack = require("webpack");
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = {
  context: __dirname,
  mode: 'production',
  entry: __dirname + "/js/init.js",
  output: {
    path: __dirname + "/dist",
    filename: "bundle.js"
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery",
      noUiSlider: 'nouislider',
      Vue: 'vue'
    }),
    new ExtractTextPlugin("bundle.css")
  ],
  module: {
    'rules': [
      {
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: {
            loader: "css-loader",
            options: {
              minimize: true
            }
          }
        })
      }
      , {
        test: /\.less$/,
        use: ExtractTextPlugin.extract({
          fallback: "style-loader",
          use: {
            loader: "css-loader!less-loader",
          }
        })
      }, {
        test: /\.(png|jpe?g|gif|cur)$/,
        loader: 'url-loader?limit=8192&name=imgs/[name]-[hash].[ext]'
      }
    ]
  }
};

Answer

Ishan Gulati picture Ishan Gulati · Aug 9, 2018

Use OptimizeCSSAssetsPlugin to minify css assets, extractors are used to separate output assets only. Note that minification works with production mode i.e. make sure to pass "--mode production" in the webpack build command.

    {....,
        optimization: {
                minimizer: [
                   //Incase you want to uglify/minify js
                    new UglifyJsPlugin({
                        cache: true,
                        parallel: true,
                        sourceMap: true
                    }),
                    new OptimizeCSSAssetsPlugin({
                        cssProcessorOptions: { discardComments: { removeAll: true } },
                        canPrint: true
                    })
                ]
         }
    ....}