天天看點

Angular——子產品懶加載

惰性加載可以通過把應用拆分成多個釋出包,并按需加載它們,來加速應用的啟動時間。

主子產品 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 { }