惰性加载可以通过把应用拆分成多个发布包,并按需加载它们,来加速应用的启动时间。
主模块 home.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { NormalComponent } from './normal/normal.component';
import { NormalModule } from './normal/normal.module';
import { HomeComponent } from './home.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'normal', component: NormalComponent }, // 普通加载
{ path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule' } // 懒加载
];
@NgModule({
imports: [
CommonModule,
NormalModule,
RouterModule.forChild(routes)
],
declarations: [HomeComponent]
})
export class HomeModule { }
懒加载模块 lazy.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CommonModule } from '@angular/common';
import { LazyComponent } from './lazy.component';
@NgModule({
imports: [
CommonModule,
RouterModule.forChild([{ path: '', component: LazyComponent }])
],
declarations: [LazyComponent]
})
export class LazyModule { }
网友评论