Webpack: Code Splitting by Routes

Bobby @ fiskal.app
2 min readFeb 8, 2016

--

If you like this article, check out my work to solve personal finance at fiskal.app.

Webpack is an incredible build tool for the web. The core concept of Webpack is to separate the code base’s structure from the deployment mechanism. At Capital One, we’re able to use Webpack to have our web app get load the page in 2 seconds over a 3G connection.

The biggest contributing factor to fast load times is a feature called Chunking or Code Splitting. All the bootstrapping code is bundled into a single file with each page as a separate file. This gives us an app that will always retain a relatively fixed page load regardless of how many features we add. Whether there are 2 pages or 200,000 pages, the total download to navigate to any page will be relatively the unchanged.

In Webpack this is done by hinting in the code base that there are optional break point. This is done by the require.ensure syntax. The best place to setup chunking is in the router. Here is an example of how to break up routes.

In react-router used the getComponents function with Webpack’s require.ensure syntax to allow lazy loading.

Now that the routes are setup, we need to tell Webpack to create separate JS files in the build process. Here are the salient parts from our Webpack config. The globals all go into a single lib.js file and each page in the route will be a separate .js file.

If that seems like a lot of work, it is. Check out our React/Webpack starter kit. It has code chunking and more already setup. In Megatome, code splitting with react-router is always built-in. Just add any routes you like in the routes.js file. In dev mode it will use HMR but running the build script will handle the code splitting. Megatome has a regular webpack.config.js file as well. You can make any tweaks to it you’ll find around the web. There are 4 standard npm scripts.

npm start      # dev mode w/ HMR and optional back-end server
npm run build # standard production build w/ minify & chunking
npm run embed # everything into a single file (great for CMSs)
npm run render # server-side pre-booting and rendering

Here are the options available in the high level config. This config simplifies some of the complications and allow for very quick setup for multiple environment.

--

--