Preventing duplication with SplitChunksPlugin

SplitChunksPlugin allows the extraction of common dependencies into entry chunks, either existing or new. In the following walk-through, this method will be used to deduplicate the lodash dependency from the preceding example.

The following is a code snippet from the webpack.config.js file, found in the preceding example's project directory. This example shows the configuration options needed to use the plugin:

  1. We will begin by ensuring that our configuration is coded to the same configuration as in the preceding example:
const path = require('path');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js',
another: './src/another-module.js'
},
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
optimization: {
splitChunks: {
chunks: 'all'
}
}
};

Using the optimization.splitChunks configuration, the duplicate dependency should now be removed from index.bundle.js and another.bundle.js. lodash has been separated into a separate chunk and the main bundle.

  1. Next, perform npm run build:
...
Asset Size Chunks Chunk Names
another.bundle.js 5.95 KiB another [emitted] another
index.bundle.js 5.89 KiB index [emitted] index
vendors~another~index.bundle.js 547 KiB vendors~another~index [emitted] vendors~another~index
Entrypoint index = vendors~another~index.bundle.js index.bundle.js
Entrypoint another = vendors~another~index.bundle.js another.bundle.js
...

There are other community-developed loaders and plugins that can be used to split code. Some of the more notable examples are as follows:

  • bundle-loader: Used to split code and lazy-load the resulting bundles
  • promise-loader: Similar to bundle-loader but uses promises
  • mini-css-extract-plugin: Useful for splitting CSS from the main application

Now, with a firm understanding of how duplication can be prevented, we will move on to a more difficult topic—dynamic imports. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.131.168