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:

/app

app.component.ts

app.component.html

app.module.ts

app.routing.ts

/home

home.component.ts

home.component.html

home.module.ts

home.routing.ts

/+about --> Lazy loaded module

about.component.ts

about.component.html

about.module.ts

about.routing.ts

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

webpack.config.js loaders: [

{

test: /\.ts$/,

loaders: [

‘awesome-typescript-loader’,

‘angular2-template-loader’,

‘angular2-router-loader’]

},

...

]

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.

app.routing.ts const routes: Routes = [

{ path: '', redirectTo: '/home', pathMatch: 'full',

{ path: 'about', loadChildren: './+about/about.module#AboutModule' }

];

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.

./+about/about.routing.ts const routes: Routes = [

{ path: '', component: AboutComponent },

];

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