0%

angular-cli lazy loading 懒加载

安装 angular-cli

npm install -g @angular/cli

如果你使用的的是 beta.28或更以前的版本升级前需要先卸载 angular-cli,因为 angular-cli 已经变成了 @angular/cli

升级 Angular CLI,你需要同时升级全局的和项目本地目录中的,避免出现一些难以排查的问题

安装完成后运行命令?ng version?我现在使用的版本是 1.0.0 ,安装时候请注意 node 的版本

 

新建项目

使用命令

ng new angular-cli-lazyloading

注意:npm 包下载安装会需要一段时间,请耐心等待出现 successfully created

 

路由

我们参照官方的教程(https://www.angular.cn/docs/ts/latest/tutorial/toh-pt5.html)来配置一下路由实现 home 页和 about 页面的切换

我们创建两个组件,home 和 about

在这里我还创建了一个 about 的 module,随后的懒加载会用到

app.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { AppComponent } from "./app.component";
import { HomeComponent } from "./home/home.component";
import { RouterModule, Routes } from "@angular/router";
import { AboutComponent } from "./about/about.component";

const rootRoutes: Routes = [
{ path: "", redirectTo: "/home", pathMatch: "full" },
{ path: "home", component: HomeComponent },
{ path: "about", component: AboutComponent },
];

@NgModule({
declarations: [AppComponent, HomeComponent, AboutComponent],
imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(rootRoutes),
],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

 

app.component.html

1
2
3
4
5
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

 

修改以上代码就可以实现一个简单的路由功能

 

懒加载 Lazy Loading

现在开始我们修改代码来实现懒加载

首先我们来修改稍早建立的 about.module.ts

 

然后修改 app.module.ts 的路由部分

完成!就是这么简单,通过 loadChildren 来实现懒加载

 

现在运行 ng serve 看看效果

可以看到在加载 about 的时候多了一个 0.chunk.js 的文件