
Demystifying code splitting
In our last blog post on Demystifying Webpack, we touched on a few optimization techniques to reduce the bundle size. This week, we will use a sample Webpack project to demonstrate one of them: code splitting in the form of common chunk extraction.
Baseline
The sample Webpack project has two entry points, the home page and my team page.

Webpack config of entry and output,
entry: {
main: './index.js',
'my-team': './my-team/index.js'
}
output: {
filename: 'bundle.[name].[contenthash].js'
}
Code splitting
Since the two pages are in the same npm project, it means they will share dependencies. Given this project uses React, it is embedded in both bundles.
If only our users downloaded React once the first time they visited either the home page or my team page, that would be great. This is where the Webpack split chunks plugin comes into play.
The split chunks plugin can be used in many ways, but we’ll use it in its most simple form. Just chunk everything.

Webpack config to chunk everything,
optimization: {
splitChunks: {
chunks: 'all'
}
}
We compare the code split bundle size against the baseline and discover we’ve extracted 400 KB common npm dependencies into a shared bundle! Note these are the gzipped sizes. You do have compression turned on for your CDN right?

Another neat thing with code splitting into more bundles is the browser can download them in parallel. Consider how the browser works in these two scenarios,
Baseline
- User visits home page
- Download 468 KB
- User visits my team page
- Download 512 KB
Code split
- User visits home page
- Download 60 KB, 16 KB, 400 KB in parallel,
total time = max(60, 16, 400) = 400
- User visits my team page
- Download 44 KB, 72 KB, 400 KB (cached) in parallel,
total time = max(44, 72, 0) = 72
Thus the bundle size doesn’t even tell the full story. From the user’s perspective code-splitting results in (400 + 72) / (980) = 48% of the load time!
This assumes the user’s internet has the capacity to download all the bundles in parallel. There are also limits to how many resources browsers will download in parallel per domain. Real-world constraints need to be tested.
If you want to learn more about Webpack or how to optimize it, you’re in luck. Battlefy is hiring.