Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Plugins and Assets

MiniCssExtractPlugin

Move CSS out of JavaScript into real .css files with MiniCssExtractPlugin, switch between style-loader and the plugin by mode, add CssMinimizerPlugin, hash names and split CSS by chunk.

In CSS and Style Loaders you saw that style-loader injects CSS using JavaScript. That is fine in development, but in production it has costs: the page shows no styles until the JavaScript has downloaded and run, causing a flash of unstyled content, and the CSS cannot be cached or downloaded separately from the JS.

mini-css-extract-plugin fixes this. It takes the CSS that css-loader produced and writes it to real .css files, then replaces the style-loader step with a loader that points the module at the extracted file.

Terminal
npm install --save-dev mini-css-extract-plugin css-minimizer-webpack-plugin

Configuration

JavaScript
const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader'],
      },
    ],
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: '[name].[contenthash:8].css',
      chunkFilename: '[id].[contenthash:8].css',
    }),
  ],
};

Two pieces must be used together: the loader (MiniCssExtractPlugin.loader) replaces style-loader in the chain, and the plugin instance does the writing. Using the loader without the plugin throws an error, and using both style-loader and the extract loader in one rule is a mistake: pick one.

filename names CSS for entries, chunkFilename for lazy-loaded chunks (Output and Filenames). With HtmlWebpackPlugin (previous lesson) the resulting <link> tag is added to the HTML for you.

Node.js Stand-in: collect CSS from modules into one file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Different loaders in development and production

Extraction costs you hot reloading of CSS in some setups, so many projects only extract in production:

JavaScript
module.exports = (env, argv) => {
  const isProd = argv.mode === 'production';
  return {
    module: {
      rules: [{
        test: /\.s?css$/i,
        use: [
          isProd ? MiniCssExtractPlugin.loader : 'style-loader',
          'css-loader',
          'sass-loader',
        ],
      }],
    },
    plugins: isProd ? [new MiniCssExtractPlugin({ filename: '[name].[contenthash:8].css' })] : [],
  };
};

This pattern uses the function config from The Webpack Configuration File. Development keeps style-loader; production writes files.

Minifying CSS

Webpack's production minimizer (Terser) only handles JavaScript. To minify CSS, add CssMinimizerPlugin to optimization.minimizer. Because setting minimizer replaces the defaults, keep Terser by listing '...'.

JavaScript
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [
      '...',                    // keep the default JS minimizer
      new CssMinimizerPlugin(),
    ],
  },
};

Minimization only runs when optimization.minimize is true, which is the default for mode: 'production' (Build Modes). To test it in development, set minimize: true.

Node.js Stand-in: a tiny CSS minifier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real minifiers (cssnano, Lightning CSS) also merge rules and shorten colors safely; this toy only strips whitespace.

Splitting CSS per chunk and ordering

If you use dynamic imports (chapter 5), each lazy chunk can have its own CSS file, which loads together with the chunk. The plugin handles the <link> insertion at runtime.

CSS order matters: later rules override earlier ones with equal specificity. When two chunks import the same file in different orders, you may see an "Conflicting order" warning. Fix it by importing shared styles in the same order everywhere, or set ignoreOrder: true in the plugin options when you use CSS Modules, where order does not matter.

Source maps and other options

  • Set sourceMap: true on css-loader (and Sass/PostCSS loaders) and a matching devtool to map minified CSS back to sources (Source Maps).
  • insert, attributes and linkType change how lazy CSS <link> tags are created, for example to add a CSP nonce.
  • runtime: false skips the runtime code if you load all CSS yourself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What problem does extracting CSS into a file solve compared to style-loader?

    A real CSS file loads in parallel with JS and is cacheable; style-loader waits for JS.
  2. 2. Which two parts of MiniCssExtractPlugin must be used together?

    The loader marks CSS to extract; the plugin writes the files.
  3. 3. Why does the minimizer array include '...' in the CssMinimizerPlugin example?

    Setting optimization.minimizer replaces the defaults, and '...' re-includes them.
  4. 4. When is CSS minimization active by default?

    Minimizers run only when minimize is on, and the CSS minimizer must be added explicitly.

Summary

  • MiniCssExtractPlugin writes CSS to files; use its loader instead of style-loader and add the plugin.
  • Extract in production, keep style-loader in development with a function config.
  • Add CssMinimizerPlugin and keep '...' to retain the JavaScript minimizer.
  • Lazy chunks get their own CSS; mind import order and the ignoreOrder option.

Next: Asset Modules: Images, Fonts and Files