WikipediaWikipedia

Name CSS Split Chunks using MiniCssExtractPlugin

Estimated 1 minute read · Thursday, 17 March 2022

React: 17.0.2 Webpack: 5.67.0 Webpack CLI: 4.9.1 mini-css-extract-plugin 2.5.3

Snippet

Copy
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
  ...
  output: {
    optimization: {
      ...
      minimizer: [
        new MiniCssExtractPlugin({
          chunkFilename: (pathData) => {
            return `${pathData.chunk.id}.[contenthash].css`;
          },
        }),
      ],
    },
  },
  ...
};

Objective

Bust the cache for CSS files that are emitted on build using Webpack 5 with Split Chunks.

Set up

  1. import one or more CSS files inside a React component.
  2. A single CSS file for that chunk is emitted on build.
  3. This file will be requested when the component is imported downstream.
  4. When it is requested over HTTP the file is most likely cached and will need to be busted upon new releases.

Solution

Configure MiniCssExtractPlugin, using the snippet above, by assigning a naming function to the chunkFilename attribute on the webpack config file.

The [contenthash] placeholder produces the md4-hash of the output file content (e.g. [contenthash].js -> 4ea6ff1de66c537eb9b2.js). See more.

We use essential cookies to make our site work. With your consent, we may also use non-essential cookies to improve user experience and analyze website traffic. By clicking 'Accept', you agree to our website's cookie use as described in our Privacy Policy.