It’s possible to split out your NPM dependencies to a separate bundle with Webpack. The reason for doing this is that dependencies don’t change as often as the other code, and can therefore be cached longer by the browsers.

The documentation for this can be found here and here. The docs are pretty good, but there is one area where the docs are lacking: what to do with the generated files?

When you follow the guide your you will have a Webpack script that generates three bundle files: main.HASH.js, vendor.HASH.js, and manifest.HASH.js . You will also have two manifest files: chunk-manifest.json and manifest.json

That’s a lot of files compared to what had before! The docs doesn’t describe in much detail what to do with these files. Here is a more in depth explanation. Be sure to read all the way because the most potentially confusing part is described at the bottom! :)

The contents of chunk-manifest.json should be assigned to a variable called window.webpackManifest at the top of your server side generated HTML file. It should be done at the top of the page inside the HEAD-tag.

It looks something like this (depending on the template language you use):

< script > window . webpackManifest = { { { webpackChunkManifest } } } < / script >

Webpack will generate this file if you use the webpack-manifest-plugin. The docs describes a few different alternatives but this is what I picked and it worked great for my needs!

The manifest.json file will include the file names of your generated bundles including the hash. You will use this for including the bundles on the HTML file described in the next step. If you picked another plugin or wrote your own that’s fine. I am sure they are all good choices :)

3. The bundle files

And now to the thing that potentially could lead to most confusion! Are you ready? Ok, lets go.

All the bundle files should be included with script tags in your HTML files. It’s very important to include the files in the correct order. If you insert them in the wrong order you will get a cryptic error:

The correct order is: manifest, vendor, app. I use handlebars, so for me it looks like this:

< script src = "/{{webpackManifest.[manifest.js]}}" > < / script > < script src = "/{{webpackManifest.[vendor.js]}}" > < / script > < script src = "/{{webpackManifest.[app.js]}}" > < / script >

The full path including the hashes are fetch from the manifest.json file described in previous step.

Conclusion

Code splitting is not to difficult to get set up using Webpack, but the error messages when getting things wrong could be improved. If I knew the things described in this blog post when setting up code splitting, it would have saved me at least 2 hours. Now that this post exist, I hope it can save you some time!

If you still have questions or comments, I might be able to help! Email me or tweet me!