Code splitting with React Router

I wrote about code splitting and lazy loading with webpack in general in the previous post

With code splitting we can significantly reduce the amount of bundled code fetched from backend, and also increase security of our apps.

Code splitting is vital for huge SPAs.

Suppose we have these components:

App.js // root component
IndexPage.js // Index page
Acomponent.js // First child component
Bcomponent.js // Second child component

We organize our routes like this:

import React from 'react';
import { Router, hashHistory } from 'react-router';
import App from './App.js'; // root component
import IndexPage from './IndexPage';
// plain routes
const componentRoutes = {
component: App,
path: '/',
indexRoute: {
// A single component to be rendered
// when the route matches the URL.
// It can be rendered by the
// parent route component with
// this.props.children
component: IndexPage
childRoutes: [
path: 'a',
// getComponent is same as component but asynchronous
getComponent(location, cb) {
// webpack will create
// adittional bundle file for the component
// first argument in the callback - error object
.then(module => cb(null, module.default));
path: 'b',
getComponent(location, cb) {
.then(module => cb(null, module.default));
const Routes = () => {
return (
<Router history={hashHistory} routes={componentRoutes} />
export default Routes;

Above we use plain routes syntax — that gives us additional ability to load components asynchronously with getComponent

We use System.import for lazy loading. When webpack sees the call of System.import it generates additional bundle file for that. In our case there will be 2 additional bundle files for Acomponent.js and Bcomponent.js And those bundles will be loaded only if we go to the according routes.

When your app’s bundle grows in size and initial loading of the app gets slow— this technique is one of the ways to handle the problem.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.