The Wonder of SplitChunksPlugin

Amit Joki
2 min readJun 12, 2020

--

The second week of Google Summer of Code with Wikimedia saw me exploring ways to further reduce our bundle size at WikiEduDashboard.

Our bundle size was on the upper side of 4 MB, which is a lot.

As I was searching the documentation of Webpack to optimize our bundle size, I stumbled upon a wonderful plugin SplitChunksPlugin.

Apparently the plugin is a revamped version of the community favorite CommonChunksPlugin which breathed its last when Webpack 4 deprecated it.

Webpack

So what does it do? Apparently, by default, each chunk includes all the dependencies it needs for the code to run within itself.

Webpack cleverly analyses all the entry points for shared code which is over a certain threshold, the default being 30KB.

So what does it mean? Suppose we have two entry points A, B as follows:

// A.jsimport 'biggerThan30KBPackage';
import 'trivialPackageLessThan30KB';
console.log('A entry point');// B.jsimport 'biggerThan30KBPackage';
import 'trivialPackageLessThan30KB';
console.log('B entry point');

What SplitChunksPlugin does is, it sees that biggerThan30KBPackage is being shared by two entry points and that it is larger than the threshold of the 30KB and so, it extracts the package into a separate file, say, C.js. So we end up with a single dependency that is shared between two entry points rather than having to have the dependency copied in each of the chunks drastically increasing the bundle size.

For example, if we say the size of biggerThan30KBPackage to be 35KB, then, without SplitChunksPlugin, we will get 70KB of the dependencies while with SplitChunksPlugin, we will get 35~40KB.

So what happens with those packages that are less than the threshold?

Webpack deems that trivial packages should be bundled within the chunk itself as it deems that to be more performant/optimal than trying to aggressively trying to put every shared code into a single file.

With a single config,

optimization: {
splitChunks: {
chunks: 'all',
name: 'vendors'
},
}

We managed to shave off nearly 1.1 MB off our bundle size. Now, I have just described the way where we put all the shared code in a single file (shared.js in the above case) but there are various ways it could be used, as is the case with Webpack.

You can even configure the threshold to your liking.

Head over to https://webpack.js.org/plugins/split-chunks-plugin/ to learn more on how you can tinker with it to suit your needs.

--

--