We want a shared vendor asset that contains all imported npm packages once they are used more than once. If a npm package is only used in a single entry point, leave it to be included in that asset.

You can create a entry in optimization.splitChunks.cacheGroups providing the following configuration.

module.exports = {
  //...
  optimization: {
    splitChunks: {
      cacheGroups: {
        commons: {
          name: 'vendor'
          test: /[\\/]node_modules[\\/]/,
          minChunks: 2
        }
      }
    }
  }
};

name

This is self explanatory, as it later becomes the name of the chunk produced.


test

The test key allows you to provide a matcher to determine whether or not a module should be included in this cache group. In our case we provide the following Regex so that we only include modules that come from node_modules.

/[\\/]node_modules[\\/]/

minChunks

This configuration allows you to determine a minimum number of assets it would be included in before pulling it into this cache group.

Say you have a npm package that is only used in a single entry point in your application, and that entry point is only loaded on one page. Would you really want that package to be pulled into the cache group and loaded on every page?

Probably not.

This allows you to tune how aggressively this cache group selects packages to include.

In our case, as soon as a package is included in more than one entry point we want to include it.