AngularでModuleを遅延読み込み(Lazy Loading)する方法をご紹介します。
目次
プロジェクトの作成
下記のコマンドでプロジェクトを作成します。
ng new lazyload-sample --routing
遅延読み込みするModuleの作成
遅延読み込みする`LazyModule`と`LazyComponent`を作成します。
LazyModule
ng g m lazy --routing
LazyComponent
ng g c lazy
Routingの設定
`/lazy`に遷移した時に`LazyModule`を読み込んで`LazyComponent`を表示するように設定します。
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{path: 'lazy', loadChildren: './lazy/lazy.module#LazyModule'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
lazy-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { LazyComponent } from './lazy.component';
const routes: Routes = [
{path: '', component: LazyComponent}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class LazyRoutingModule { }
これで`/lazy`に遷移した時、`LazyModule`が読み込まれて`LazyComponent`が表示されるようになりました。
遷移用のリンクを追加
`app.component.html`に`/lazy`に遷移するためのリンクを追加します。
app.component.html
Navigate to Lazy
ブラウザで確認
下記のコマンドを実行してブラウザで確認してみましょう。
ng serve

`Navigate to Lazy`をクリックすると

`lazy-lazy-module.js`が読み込まれて`LazyComponent`が表示されました。
