Using Webpack and React-router to improve performance with lazy loading

Nadav Dav
2 min readJul 16, 2016

--

Here is a nice example of code splitting and lazy loading, using Webpack and react-router.

This approach splits the application file and improves loading time significantly.

If you use react-router you probably have a routing file that looks like this:

import HomePage from "./pages/HomePage";
import AdminPage from "./pages/admin/AdminPage";
import AdminPageSettings from "./pages/admin/AdminPageSettings";
export default function routes(fromServer) {
return (
<Router history={browserHistory}>
<Route path="/" component={HomePage}/>
<Route path="/admin" component={AdminPage}/>
<Route path="/admin/settings" component={AdminSettingsPage}/>
<Router/>
)
}

The admin pages are heavy, and should not be loaded unless reaching for the `/admin` url. I have placed all these pages under a dedicated folder named `pages/admin/..`

To enable the code splitting, install the bundle-loader and add this to you webpack.config.js:

npm install --save-dev bundle-loader

&

{
...
module: { loaders: [{
// use `test` to split a single file
// or `include` to split a whole folder
test: /.*/,
include: [path.resolve(__dirname, 'pages/admin')],
loader: 'bundle?lazy&name=admin'
}]

}
...
}

This will remove all the admin related components from the main file, and move them to a new file called 1.admin.js in your destination folder.

Next, tell react-router to load it lazily:

import HomePage from "./pages/HomePage";
import AdminPage from "./pages/admin/AdminPage";
import AdminPageSettings from "./pages/admin/AdminPageSettings";
const isReactComponent = (obj) => Boolean(obj && obj.prototype && Boolean(obj.prototype.isReactComponent));

const component = (component) => {
return isReactComponent(component)
? {component}
: {getComponent: (loc, cb)=> component(
comp=> cb(null, comp.default || comp))}
};
export default function routes(fromServer) {
return (
<Router history={browserHistory}>
<Route path="/" {...component(HomePage)}/>
<Route path="/admin" {...component(AdminPage)}/>
<Route path="/admin/settings"
{...component(AdminSettingsPage)}/>
<Router/>
)
}

Thats it! Give it a spin and tell me how you like it!

One caveat that gave me trouble:

Since the lazy loading is implemented only in the router file, make sure all the files in the selected folder are loaded through the router, ie. only `pages` components.

Feel free to visit our webpage at Jolt.us.

Jolt is a marketplace for LIVE content sessions given to your team by the world’s most exceptional industry professionals, in person or online.

--

--