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.
The sample Webpack project has two entry points, the home page and my team page.
Webpack config of entry and output,
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. We are making our users suffer, having them download React redundantly for each page they visit.
Ideally our users would only download React once. Either the first time they visited or the home page or my team page. 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. The plugin will figure out the common dependencies and create common bundle of them.
Webpack config to chunk everything,
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,
total time = max(60, 16, 400) = 400
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.