5

I was setting the Webpack loaders config for .css and .scss files, I noticed that when using --mode production I'm getting minimized CSS as the final output without even using a minimizer explicitly, here's my loaders config:

{
  // Match .css or .scss
  test: /\.s?css$/,
  use: [
    isProd
    // In production extract the CSS into separate files
    ? {
      loader: MiniCssExtractPlugin.loader,
      options: {
        hmr: !isProd
      }
    }
    // In development inject the styles into the DOM
    : 'style-loader',
    {
      loader: 'css-loader'
    },
    {
      loader: 'sass-loader',
      options: {
        sourceMap: false
      }
    }
  ]
}

I'm using sass-loader with node-sass and mini-css-extract-plugin to extract the CSS into separate files, which suggests using optimize-css-assets-webpack-plugin for minimizing the CSS by overriding optimization.minimizer, but I'm already getting minimized output without installing this plugin.

To find what's causing this behavior I tried processing CSS files with and without sass-loader and I found out that sass-loader might be causing this behavior but it doesn't have any option for minimizing the CSS.

So what's causing this behavior? And do I even still need optimize-css-assets-webpack-plugin if my CSS files are minimized?

Pierre
  • 12,468
  • 6
  • 44
  • 63

2 Answers2

5

Option outputStyle in sass-loader options determines the output format of the final CSS style.
Default: nested.
For more detailed https://github.com/sass/node-sass#outputstyle
To disable minification, set this option to expanded:

{
  loader: 'sass-loader',
  options: {
    sassOptions: {
        outputStyle: 'expanded'
    }
  }
}

For minify css i reccomend plugin css-nano. It is flexible in settings. It's good work with postcss-loader.

Bluorenge
  • 89
  • 2
  • 5
2

According to the webpack docs,

webpack v4+ will minify your code by default in production mode.

So it's not sass-loader doing the minification, it's just that removing that means webpack isn't processing your SCSS into CSS and therefore not creating a file to be minified.

I'd say if you're happy with simple minification the default is probably fine for production. Other tools might give you more control over the final output including things like source maps, removing duplicate rules, dumping old prefixes, etc.

Bryce Howitson
  • 7,339
  • 18
  • 40