3

I am attempting to use the Webpack 4 Split Chunks Plugin to create multiple vendor bundles. In this case, I want to create one chunk for react/react-dom, and one chunk for react-router/react-router-dom.

When cacheGroups only contains react and vendor, the build works as expected. The bundle output is:

- index
- react
- runtime
- vendors

Likewise, if I only have cacheGroups for router and vendor it works as expected. The output is:

- index
- router
- runtime
- vendors

In either case when the chunks are created, inspecting shows the correct code for react or router in their respective cases.

BUT... it doesn't work when I include both - in this case only the router chunk is created, and react code is pushed into the index (src) bundle.

I suspect something is off in the regex patterns that is causing an invalidation of the previous cacheGroup? Any help is appreciated.

Here is my webpack config for splitChunks:

splitChunks: {
  cacheGroups: {
    react: {
      test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
      name: 'react',
      chunks: 'all'
    },
    router: {
      test: /[\\/]node_modules[\\/](react-router|react-router-dom)[\\/]/,
      name: 'router',
      chunks: 'all'
    },
    vendor: {
      test(mod) {
        // exclude anything outside node modules
        if (!mod.context.includes('node_modules')) {
          return false;
        }

        // exclude react and react-dom
        if (/[\\/]node_modules[\\/](react|react-dom)[\\/]/.test(mod.context)) {
          return false;
        }

        // exclude react-router and react-router-dom
        if (/[\\/]node_modules[\\/](react-router|react-router-dom)[\\/]/.test(mod.context)) {
          return false;
        }

        // return all other node modules
        return true;
      },
      name: 'vendors',
      chunks: 'all'
    }
  }
}
mhatch
  • 4,441
  • 6
  • 36
  • 62

2 Answers2

3

Try to this to your config:

optimization: {
    splitChunks: {
      maxInitialRequests: 4, // This one!

The default value of maxInitialRequests is 4, so if you have more than 4 bundle, it will somehow merge some of them.

Zmen Hu
  • 795
  • 3
  • 12
1

that works for me:

router: {
      test: /[\\/]node_modules[\\/](react-router|react-router-dom)[\\/]/,
      name: 'router',
      chunks: 'all',
      priority: 1,
    },
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – lemon May 17 '22 at 18:36