ANGULAR LAZY LOADING WITH WEBPACK 2

ANGULAR LAZY LOADING WITH WEBPACK 2

First create an Angular module

In this example, the about module will be lazy loaded when the user clicks on the about tab. The about.module.ts is the entry point for this feature. The module has its own component and routing.
The app will now be setup to lazy load the AboutModule.

  • import { NgModule } from ‘@angular/core’;
  • import { CommonModule } from ‘@angular/common’;
  • import { AboutRoutes } from ‘./about.routes’;
  • import { AboutComponent } from ‘./components/about.component’;
  • @NgModule({
  • imports: [
  • CommonModule,
  • AboutRoutes
  • ],
  • declarations: [
  • AboutComponent
  • ],
  • })

export class AboutModule { }
To add lazy loading to the app, the angular-router-loader npm package needs to be added to the packages.json npm file in the devDependencies.

  • “devDependencies”: {
  • “@types/node”: “7.0.0”,
  • “angular2-template-loader”: “^0.6.0”,
  • “angular-router-loader”: “^0.5.0”,

Configure the Angular 2 routing

The lazy loading routing can be added to the app.routes.ts file. The loadChildren defines the module and the class name of the module which can be lazy loaded. It is also possible to pre-load lazy load modules if required.

  • import { Routes, RouterModule } from ‘@angular/router’;
  • export const routes: Routes = [
  • { path: ”, redirectTo: ‘home’, pathMatch: ‘full’ },
  • {
  • path: ‘about’, loadChildren: ‘./about/about.module#AboutModule’,
  • }
  • ];

export const AppRoutes = RouterModule.forRoot(routes);
Update the tsconfig-aot.json and tsconfig.json files

Now the tsconfig.json for development JIT builds and the tsconfig-aot.json for AOT production builds need to be configured to load the AboutModule module.

AOT production build

The files property contains all the module entry points as well as the app entry file. The angularCompilerOptions property defines the folder where the AOT will be built into. This must match the configuration in the Webpack production config file.

  • {
  • “compilerOptions”: {
  • “target”: “es5”,
  • “module”: “es2015”,
  • “moduleResolution”: “node”,
  • “sourceMap”: false,
  • “emitDecoratorMetadata”: true,
  • “experimentalDecorators”: true,
  • “removeComments”: true,
  • “noImplicitAny”: true,
  • “suppressImplicitAnyIndexErrors”: true,
  • “skipLibCheck”: true,
  • “lib”: [
  • “es2015”,
  • “dom”
  • ]
  • },
  • “files”: [
  • “angularApp/app/app.module.ts”,
  • “angularApp/app/about/about.module.ts”,
  • “angularApp/main-aot.ts”
  • ],
  • “angularCompilerOptions”: {
  • “genDir”: “aot”,
  • “skipMetadataEmit”: true
  • },
  • “compileOnSave”: false,
  • “buildOnSave”: false
  • }

About the author

admin administrator

Leave a Reply