Grouping chunks

So far, we haven’t exactly configured anything for making chunks. We just used import function which made async chunks on its own. Let’s now focus on webpack.config.js and add some logic to create different chunks we might need besides only async chunks (as discussed previously).

You can read the documentation of SplitChunksPlugin here and how to configure it. This plugin is implemented by Webpack internally and it’s API is exposed inside optimization.splitChunks of webpack.config.js .

splitChunks contains many configurations and we are going to focus on cacheGroups first. cacheGroups tells SplitChunksPlugin to create chunks based on some conditions, for example, create a separate chunk file for all the code being imported from node_modules .

cacheGroups is a plain object with key being the name of chunk and value being some configuration of that chunk. By default, Webpack ships with vendors and default cacheGroups but let’s turn those off by setting their value to false , else it will just confuse you to understand code splitting.

// optimization

optimization : {

splitChunks: {

cacheGroups: {

default: false,

vendors: false, }

}

}

Let’s create a vendor chunk which contains all code from node_modules imported in the project. Whenever Webpack encounters import statement of npm module, it will push that code inside vendor chunk.

// optimization

optimization: {

splitChunks: {

cacheGroups: {

default: false,

vendors: false, // vendor chunk

vendor: {

// sync + async chunks

chunks: 'all', // import file path containing node_modules

test: /node_modules/

}

}

}

}

We are creating a vendor chunk which would create a chunk file from all those import statements of files coming from node_modules . test value is a RegExp which is matched against the file path of the import. When Webpack encounters an import statement whose file falls inside node_modules , it will be added to vendor chunks.

Here chunks value tells SplitChunksPlugin the nature of chunks to consider for evaluation. Its value can be initial , async or all . initial means only add files to the chunk if they are imported inside sync chunks. async means only add files to the chunk if they are imported inside async chunks.

main.js is considered as synchronous chunk (but it’s not a chunk, technically). Hence, if a chunkGroup has initial or all chunks value, then main.js will be evaluated by Webpack.

As you can see from the above animation, Webpack is creating vendor~main.main.js chunk file which contains all of our vendor code. You are free to add any other vendor files (which might not come from node_modules ) to this chunk using different test RegExp value.

By default, SplitChunksPlugin prepends key of the chunk to the name of the build file. We can avoid that by using name key and specify a different name.