<aside> πŸ§‘β€πŸŽ“ To merge duplicate modules, we must make sure module is indeed duplicated:

How to inspect bundle contents?

</aside>

To merge duplicate modules means to move a modules duplicated across multiple chunks into a separate chunk. To achieve it, the following actions are required:

1. Find duplicated modules

This can be done by looking up duplicates manually using bundle analyzer, or using the automated software, like https://statoscope.tech/. To do it, first generate stats:

yarn build --stats # using Yarn
npm run build -- --stats # using NPM

The build/bundle-stats.json will be generated as a result. Upload the file to the website, go to Duplicate modules tab at the bottom of the page:

Untitled

2. Create a new build configuration plugin

Create a next extension, declare a build configuration plugin inside. It is possible to use an exiting extension too. Follow these instructions:

How to build configuration plugins?

3. Add a new named chunk group to Webpack configuration

Inside of a build configuration plugin, add the following logic:

if (!webpackConfig.optimization.splitChunks) {
  webpackConfig.optimization.splitChunks = {};
}

webpackConfig.optimization.splitChunks.chunks = 'async';

if (!webpackConfig.optimization.splitChunks.cacheGroups) {
  webpackConfig.optimization.splitChunks.cacheGroups = {};
}

Now, for each duplicate chunk, create a new named chunk group (by providing a regular expression to test module names with):

webpackConfig.optimization.splitChunks.cacheGroups.field = {
  test: /(field)/i,
  name: 'fields'
};

<aside> πŸŽ‰ That’s how you merge duplicated modules!

</aside>