Building a bridge
WikipediaWikipedia
Gradient background

Name CSS Split Chunks using MiniCssExtractPlugin

Clarice Bouwer

Software Engineering Team Lead and Director of Cloudsure

Thursday, 17 March 2022 · Estimated 1 minute read

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.