Bundle splitting allows you to delay loading resources until they are actually needed. And Webpack and React make it surprisingly easy!
In this article we'll take a React component that's not needed on every page and move it from the main bundle into a separate bundle that can be lazy loaded.
1. Make sure your dependencies are up to date
I'm using Webpack 4, and you'll need at least react
and react-dom
version 16.6.
If you're using TypeScript you'll also want to update @types/react
to 16.6 or above.
2. Add chunkFilename and publicPath to your Webpack config
Add the two properties to the output property of your Webpack config file:
chunkFilename: "chunk-[name].[contenthash].js",
publicPath: "/assets/dist/"
Replace /assets/dist/
with the folder that contains your compiled bundles. This can also be a URL. The publicPath
is needed so that Webpack knowns where to fetch the chunk bundles from, once they are split into separate files.
While fileName
is used for independent entry bundles, chunkFilename
is used for bundles that are auto-generated by Webpack during code splitting.