Webpack: How to migrate CommonsChunkPlugin (wp3) to optimization.splitChunks (wp4)?

1.5k Views Asked by At

I'm trying to migrate to webpack4 from 3 and I'm having a really hard time migrating CommonsChunkPlugin.

On WP3, I have the following simplified configuration:

const entries = {
  client: './src/index.js',
  common1: ['lodash'],
  common2: ['react', 'react-dom']
};

module.exports = {
  ...
  entry: entries,
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['common1', 'common2'],
      minChunks: Infinity
    })
  ]
};

On WP4 I've already tried multiple combinations using optimization.splitChunks but I just can't get it to properly bundle my modules in a way that they are sharing common dependencies, like it used to be on WP3.

Here is what I used on my last try, but the final bundles are much bigger in size:

// same entries object
const entries = { ... };

module.exports = {
  ...
  entry: entries,
  optimization: {
    splitChunks: {
    minChunks: Infinity,
    chunks: 'initial',
    cacheGroups: {
      common1: { test: 'common1' },
      common2: { test: 'common2' },
      // disables the default definition of these cache groups
      vendors: false, 
      default: false
    }
  }
};
1

There are 1 best solutions below

0
On

You can simply set enforce = true and this will "force" webpack to always create chunks for the cache group.

If you're doing code splitting (using import()) then you'll want to set chunks = "all", because with "initial" you're only grouping sync modules.

And finally, if the groups "common1" and "common2" are likely to share any modules, you might consider giving one cache group a higher priority over the other, for example if "common1" is likely to be loaded first, this should have a higher priority so that "common2" does not need to be downloaded as a dependency.

Some useful links to helpfully demystify this stuff:

  1. https://medium.com/dailyjs/webpack-4-splitchunks-plugin-d9fbbe091fd0
  2. https://webpack.js.org/plugins/split-chunks-plugin
  3. https://stackoverflow.com/a/49213048/2039244

module.exports = {
  ...
  entry: entries, // entries -> entry
  optimization: {
    splitChunks: {
      cacheGroups: {
        common1: {
          test: 'common1',
          chunks: 'all',
          enforce: true
        },
        common2: {
          test: 'common2',
          chunks: 'all',
          enforce: true
        },
        // disables the default definition of these cache groups
        vendors: false, 
        default: false
      }
    }
};