how to cache bust code splits due to React lazy Suspense?

Viewed 712

Before setting up any lazy-loaded React components, this app had an overly large, unsplit main bundle.

In order to ensure clients get updated app code, the webpack config has:

plugins: [
  new HtmlWebpackPlugin({
    template: path.resolve(__dirname, 'src', 'public', 'index.html'),
    hash: true,
  }),
  ...

That causes the build's index.html to have e.g.

  <script src="/main.bundle.js?3c6c1a14d95b24dd19cc">

where the hash in the query is generated randomly at build time.

Then adding React lazy-loading, the bundle is split for those components, which by itself is good.

But I keep getting cached versions of those split components rather than the latest version, and I wonder how to cache bust the application splits.

1 Answers

I found changing the webpack config's output.filename to include [contenthash] causes all the bundle split js files to have a hash code, then the HtmlWebpackPlugin doesn't need the hash option.

  output: {
    filename: '[name].[contenthash].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    publicPath: '/',
  },

According to webpack doc, The contenthash substitution will add a unique hash based on the content of an asset. When the asset's content changes, contenthash will change as well.

Related