Angular 2 lazy loading with Webpack

David Den Toom
Oct 1, 2016 · 2 min read

It took me some time to figure out how to setup lazy loading with Angular 2 in combination with Webpack, therefore I wrote this article to hopefully help you understand how to setup lazy loading.

TLDR: Github link

What do we want to achieve?

Lets assume we have two pages in our application, “home” and “about”. Some people might never reach the about page, so it makes sense to only serve the load of the about page to people that actually need it. This is where we will use lazy loading.

Project setup:

/+about --> Lazy loaded module

Step 1: Install the loader

We will use the angular2-router-loader. Install it with the following command:

npm install angular2-router-loader — save-dev

Now we need to add the loader to our configuration file of Webpack


Step 2: Configure the routing in the upper component

Normally you would configure the routing in the module itself that you create. For example, if its a about page you would declare the about route in the about module, not in the upper component. But because this is a lazy loaded module, we will configure the routing in the upper component where the module will be called from.


Here we configure a route “about”, and tell Angular to dynamically load the about module when someone navigates to the “about” route. The #AboutModule refers to the name of the module. The + in front of the about folder is a naming convention for modules that are being lazy loaded.

Step 3: Create the Lazy Module

Lazy Modules work almost the the same as non-lazy modules. There is one big difference however. Since we already declared the about (/about) path in the upper module, we don’t need to define that path again. What we do need to do, is configure the default component that should be loaded.


That’s it! If you run the application and navigate to the about route, you will see that a new chunk is loaded.

David Den Toom

Written by

Developer at Passionate People