ng2 lazy loading with webpack

Since alpha release of Angular2, I was very concerned about lazy loading in angular2. I spent my time to know how can we do lazy loading with webpack.

So I am going to tell you how can we do this in simple steps.

Assuming, you have setup your application with webpack.


Step1: Install angular2-router-loader

There are many webpack plugins available over the npm. But this one is my favourite and having good support and documentation.

npm install angular2-router-loader — save-dev

Now, we need to add this loader to our webpack configuration.

webpack.config.js
loaders: [
{
test: /\.ts$/,
loaders: [ ‘angular2-router-loader’ ]
}
]

Step 2: Configure the routing in the root component

Generally, you would create the route in module itself that you create. Let’s assume you have page login, you would declare its route in login module not in root component.

Since it is a lazy loaded application we need to define the reference in root component routes.

We will configure the route in root component routing where it will be called.

routing.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'login', loadChildren: './routes/login/login.module#LoginModule' }
];
@NgModule({
declarations: [ RootComponent ],
imports: [
BrowserModule,
RouterModule.forRoot(routes)
],
exports: [

],
bootstrap: [
RootComponent
],
providers: [
]
})
export class RootModule {}

I have assumed you have two pages, home and login. Where login is only lazy loaded page.

Step 3: Create lazy module

Lazy module works almost same as non-lazy module. There is one main difference the we have already declared the path in root component so we don’t need to write the whole path again.

This route will only state about which component should be loaded on call of this module.

Ultimately, routes definition clubs component with url so we need to define at module level.

./routes/login/login.module.ts
const routes: Routes = [
{ path: '', component: LoginComponent }
];
@NgModule({
declarations: [ LoginComponent ],
imports: [
RouterModule.forChild(routes)
],
exports: [

],
providers: [
]
})
export class LoginModule {}

So this way we can achieve the lazy loading with webpack.

If you liked this, click the ❤️ below so other people will see this here on Medium.

One clap, two clap, three clap, forty?

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