Webpack: Understanding Chunks And Code Splitting

- 1 answer

I've been using React more recently and have started trying to incorporate Webpack into my workflow. However, I'm trying to understand more about the tool (unfortunately, the documentation isn't very good at explaining what different aspects mean).

At a high level, I understand that Webpack allows you to create a bundled JavaScript file so that you can write code in multiple files but have 1 file loaded into your script tag in HTML. What are chunks in webpack and how does it relate to this bundling process?

Also, webpack has been touted as being able to code split - what exactly does this mean and can you guys provide an example?



"Chunks" are parts of your code that get, in a sense, required on demand from the server. So you can have one main deliverable that loads the site, but load additional resources as the user starts to browse around.

Practically, you do this by defining a split point. This tells webpack to put the code needed to run the code path within that split point (i.e. a function) in its own file. Webpack will then factor out the modules that are common to that split chunk and the main file and put it into the main file to avoid duplicating vendor code (in other words, the chunk probably won't stand alone). Now Webpack generates two files: the main file, and an additional chunk. When the chunk's code path gets hit, the main file will pull in the additional chunk off the wire. From the developer's perspective, this all happens with a require, which makes it very easy to reason.

One of the most common uses is to chunk router code. There is a working example in the react-router docs, but the general idea is that you load your initial routes into the main file, and all subsequent or child routes can be in their own chunks and only get downloaded when the user hits those routes, increasing performance (potentially). The example code is a great way to grok how this works because you can watch the files get pulled off the wire when you hit the routes.

Anyhow, code chunking is an awesome feature.

All that said, be very wary of premature optimization. It can kill productivity. The best advice is to get running with Webpack without any code chunking, and then add code chunking when you require the performance (for example when you note that a feature or section of your site is heavy but rarely used).

PS: If you have more specific questions, I'm happy to amend this answer. If you're curious, though, check out the react-router link above.