填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

惰性加载的特性模块

Lazy-loading feature modules

高层视角

High level view

默认情况下,NgModule 都是急性加载的,也就是说它会在应用加载时尽快加载,所有模块都是如此,无论是否立即要用。对于带有很多路由的大型应用,考虑使用惰性加载 —— 一种按需加载 NgModule 的模式。惰性加载可以减小初始包的尺寸,从而减少加载时间。

By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules, whether or not they are immediately necessary. For large apps with lots of routes, consider lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.

如果需要本页描述的具有两个惰性加载模块的范例应用,参见在线例子 / 下载范例

For the final sample app with two lazy-loaded modules that this page describes, see the在线例子 / 下载范例.

建立惰性加载的特性模块有两个主要步骤:

There are two main steps to setting up a lazy-loaded feature module:

  1. 使用 --route 标志,用 CLI 创建特性模块。

    Create the feature module with the CLI, using the --route flag.

  2. 配置相关路由。

    Configure the routes.

建立应用

Set up an app

如果你还没有应用,可以遵循下面的步骤使用 CLI 创建一个。如果已经有了,可以直接跳到 配置路由部分。 输入下列命令,其中的 customer-app 表示你的应用名称:

If you don’t already have an app, you can follow the steps below to create one with the CLI. If you already have an app, skip to Configure the routes. Enter the following command where customer-app is the name of your app:

ng new customer-app --routing
      
      ng new customer-app --routing
    

这会创建一个名叫 customer-app 的应用,而 --routing 标识生成了一个名叫 app-routing.module.ts 的文件,它是你建立惰性加载的特性模块时所必须的。 输入命令 cd customer-app 进入该项目。

This creates an app called customer-app and the --routing flag generates a file called app-routing.module.ts, which is one of the files you need for setting up lazy loading for your feature module. Navigate into the project by issuing the command cd customer-app.

--routing 选项需要 Angular/CLI 8.1 或更高版本。 请参阅保持最新

The --routing option requires Angular/CLI version 8.1 or higher. See Keeping Up to Date.

创建一个带路由的特性模块

Create a feature module with routing

接下来,您将需要一个包含路由的目标组件的特性模块。 要创建它,在终端中输入如下命令,其中 customers 是特性模块的名称。加载 customers 特性模块的路径也是 customers,因为它是通过 --route 选项指定的:

Next, you’ll need a feature module with a component to route to. To make one, enter the following command in the terminal, where customers is the name of the feature module. The path for loading the customers feature modules is also customers because it is specified with the --route option:

ng generate module customers --route customers --module app.module
      
      ng generate module customers --route customers --module app.module
    

这将创建一个 customers 文件夹,在其 customers.module.ts 文件中定义了新的可惰性加载模块 CustomersModule。该命令会自动在新特性模块中声明 CustomersComponent

This creates a customers folder with the new lazy-loadable module CustomersModule defined in the customers.module.ts file. The command automatically declares the CustomersComponent inside the new feature module.

因为这个新模块想要惰性加载,所以该命令不会在应用的根模块 app.module.ts 中添加对新特性模块的引用。 相反,它将声明的路由 customers 添加到以 --module 选项指定的模块中声明的 routes 数组中。

Because the new module is meant to be lazy-loaded, the command does NOT add a reference to the new feature module in the application's root module file, app.module.ts. Instead, it adds the declared route, customers to the routes array declared in the module provided as the --module option.

const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) } ];
src/app/app-routing.module.ts
      
      const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  }
];
    

注意,惰性加载语法使用 loadChildren,其后是一个使用浏览器内置的 import('...') 语法进行动态导入的函数。 其导入路径是到当前模块的相对路径。

Notice that the lazy-loading syntax uses loadChildren followed by a function that uses the browser's built-in import('...') syntax for dynamic imports. The import path is the relative path to the module.

添加另一个特性模块

Add another feature module

使用同样的命令创建第二个带路由的惰性加载特性模块及其桩组件。

Use the same command to create a second lazy-loaded feature module with routing, along with its stub component.

ng generate module orders --route orders --module app.module
      
      ng generate module orders --route orders --module app.module
    

这将创建一个名为 orders 的新文件夹,其中包含 OrdersModuleOrdersRoutingModule 以及新的 OrdersComponent 源文件。 使用 --route 选项指定的 orders 路由,用惰性加载语法添加到了 app-routing.module.ts 文件内的 routes 数组中。

This creates a new folder called orders containing the OrdersModule and OrdersRoutingModule, along with the new OrdersComponent source files. The orders route, specified with the --route option, is added to the routes array inside the app-routing.module.ts file, using the lazy-loading syntax.

const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) } ];
src/app/app-routing.module.ts
      
      const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  }
];
    

建立 UI

Set up the UI

虽然你也可以在地址栏中输入 URL,不过导航 UI 会更好用,也更常见。 把 app.component.html 中的占位脚本替换成一个自定义的导航,以便你在浏览器中能轻松地在模块之间导航。

Though you can type the URL into the address bar, a navigation UI is easier for the user and more common. Replace the default placeholder markup in app.component.html with a custom nav so you can easily navigate to your modules in the browser:

<h1> {{title}} </h1> <button routerLink="/customers">Customers</button> <button routerLink="/orders">Orders</button> <button routerLink="">Home</button> <router-outlet></router-outlet>
app.component.html
      
      <h1>
  {{title}}
</h1>

<button routerLink="/customers">Customers</button>
<button routerLink="/orders">Orders</button>
<button routerLink="">Home</button>

<router-outlet></router-outlet>
    

要想在浏览器中看到你的应用,就在终端窗口中输入下列命令:

To see your app in the browser so far, enter the following command in the terminal window:

ng serve
      
      ng serve
    

然后,跳转到 localhost:4200,这时你应该看到 customer-app 和三个按钮。

Then go to localhost:4200 where you should see customer-app and three buttons.

这些按钮生效了,因为 CLI 会自动将特性模块的路由添加到 app.module.ts 中的 routes 数组中。

These buttons work, because the CLI automatically added the routes to the feature modules to the routes array in app.module.ts.

导入与路由配置

Imports and route configuration

CLI 会将每个特性模块自动添加到应用级的路由映射表中。 通过添加默认路由来最终完成这些步骤。 在 app-routing.module.ts 文件中,使用如下命令更新 routes 数组:

The CLI automatically added each feature module to the routes map at the application level. Finish this off by adding the default route. In the app-routing.module.ts file, update the routes array with the following:

const routes: Routes = [ { path: 'customers', loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule) }, { path: 'orders', loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule) }, { path: '', redirectTo: '', pathMatch: 'full' } ];
src/app/app-routing.module.ts
      
      const routes: Routes = [
  {
    path: 'customers',
    loadChildren: () => import('./customers/customers.module').then(m => m.CustomersModule)
  },
  {
    path: 'orders',
    loadChildren: () => import('./orders/orders.module').then(m => m.OrdersModule)
  },
  {
    path: '',
    redirectTo: '',
    pathMatch: 'full'
  }
];
    

前两个路径是到 CustomersModuleOrdersModule 的路由。 最后一个条目则定义了默认路由。空路径匹配所有不匹配先前路径的内容。

The first two paths are the routes to the CustomersModule and the OrdersModule. The final entry defines a default route. The empty path matches everything that doesn't match an earlier path.

特性模块内部

Inside the feature module

接下来,仔细看看 customers.module.ts 文件。如果您使用的是 CLI,并按照此页面中的步骤进行操作,则无需在此处执行任何操作。

Next, take a look at the customers.module.ts file. If you’re using the CLI and following the steps outlined in this page, you don’t have to do anything here.

import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CustomersRoutingModule } from './customers-routing.module'; import { CustomersComponent } from './customers.component'; @NgModule({ imports: [ CommonModule, CustomersRoutingModule ], declarations: [CustomersComponent] }) export class CustomersModule { }
src/app/customers/customers.module.ts
      
      import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CustomersRoutingModule } from './customers-routing.module';
import { CustomersComponent } from './customers.component';

@NgModule({
  imports: [
    CommonModule,
    CustomersRoutingModule
  ],
  declarations: [CustomersComponent]
})
export class CustomersModule { }
    

customers.module.ts 文件导入了 customers-routing.module.tscustomers.component.ts 文件。 @NgModuleimports 数组中列出了 CustomersRoutingModule ,让 CustomersModule 可以访问它自己的路由模块。CustomersComponent 位于 declarations 数组中,这意味着 CustomersComponent 属于 CustomersModule

The customers.module.ts file imports the customers-routing.module.ts and customers.component.ts files. CustomersRoutingModule is listed in the @NgModule imports array giving CustomersModule access to its own routing module. CustomersComponent is in the declarations array, which means CustomersComponent belongs to the CustomersModule.

然后,app-routing.module.ts 会使用 JavaScript 的动态导入功能来导入特性模块 customers.module.ts

The app-routing.module.ts then imports the feature module, customers.module.ts using JavaScript's dynamic import.

专属于特性模块的路由定义文件 customers-routing.module.ts 将导入在 customers.component.ts 文件中定义的自有特性组件,以及其它 JavaScript 导入语句。然后将空路径映射到 CustomersComponent

The feature-specific route definition file customers-routing.module.ts imports its own feature component defined in the customers.component.ts file, along with the other JavaScript import statements. It then maps the empty path to the CustomersComponent.

import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { CustomersComponent } from './customers.component'; const routes: Routes = [ { path: '', component: CustomersComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class CustomersRoutingModule { }
src/app/customers/customers-routing.module.ts
      
      import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CustomersComponent } from './customers.component';


const routes: Routes = [
  {
    path: '',
    component: CustomersComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CustomersRoutingModule { }
    

这里的 path 设置为空字符串,因为 AppRoutingModule 中的路径已经设置为 customers,因此,CustomersRoutingModule 中的此路由已经位于 customers 这个上下文中。此路由模块中的每个路由都是其子路由。

The path here is set to an empty string because the path in AppRoutingModule is already set to customers, so this route in the CustomersRoutingModule, is already within the customers context. Every route in this routing module is a child route.

另一个特性模块中路由模块的配置也类似。

The other feature module's routing module is configured similarly.

import { OrdersComponent } from './orders.component'; const routes: Routes = [ { path: '', component: OrdersComponent } ];
src/app/orders/orders-routing.module.ts (excerpt)
      
      import { OrdersComponent } from './orders.component';

const routes: Routes = [
  {
    path: '',
    component: OrdersComponent
  }
];
    

确认它工作正常

Confirm it’s working

你可以使用 Chrome 开发者工具来确认一下这些模块真的是惰性加载的。 在 Chrome 中,按 Cmd+Option+i(Mac)或 Ctrl+Shift+j(PC),并选中 Network 页标签。

You can check to see that a module is indeed being lazy loaded with the Chrome developer tools. In Chrome, open the dev tools by pressing Cmd+Option+i on a Mac or Ctrl+Shift+j on a PC and go to the Network Tab.

点击 Orders 或 Customers 按钮。如果你看到某个 chunk 文件出现了,就表示一切就绪,特性模块被惰性加载成功了。Orders 和 Customers 都应该出现一次 chunk,并且它们各自只应该出现一次。

Click on the Orders or Customers button. If you see a chunk appear, everything is wired up properly and the feature module is being lazy loaded. A chunk should appear for Orders and for Customers but will only appear once for each.

要想再次查看它或测试本项目后面的行为,只要点击 Network 页左上放的 清除 图标即可。

To see it again, or to test after working in the project, clear everything out by clicking the circle with a line through it in the upper left of the Network Tab:

然后,使用 Cmd+r(Mac) 或 Ctrl+r(PC) 重新加载页面。

Then reload with Cmd+r or Ctrl+r, depending on your platform.

forRoot()forChild()

forRoot() and forChild()

你可能已经注意到了,CLI 会把 RouterModule.forRoot(routes) 添加到 AppRoutingModuleimports 数组中。 这会让 Angular 知道 AppRoutingModule 是一个路由模块,而 forRoot() 表示这是一个根路由模块。 它会配置你传入的所有路由、让你能访问路由器指令并注册 RouterforRoot() 在应用中只应该使用一次,也就是这个 AppRoutingModule 中。

You might have noticed that the CLI adds RouterModule.forRoot(routes) to the AppRoutingModule imports array. This lets Angular know that the AppRoutingModule is a routing module and forRoot() specifies that this is the root routing module. It configures all the routes you pass to it, gives you access to the router directives, and registers the Router service. Use forRoot() only once in the application, inside the AppRoutingModule.

CLI 还会把 RouterModule.forChild(routes) 添加到各个特性模块中。这种方式下 Angular 就会知道这个路由列表只负责提供额外的路由并且其设计意图是作为特性模块使用。你可以在多个模块中使用 forChild()

The CLI also adds RouterModule.forChild(routes) to feature routing modules. This way, Angular knows that the route list is only responsible for providing additional routes and is intended for feature modules. You can use forChild() in multiple modules.

forRoot() 方法为路由器管理全局性的注入器配置。 forChild() 方法中没有注入器配置,只有像 RouterOutletRouterLink 这样的指令。 欲知详情,参见单例服务章的 forRoot() 模式小节。

The forRoot() method takes care of the global injector configuration for the Router. The forChild() method has no injector configuration. It uses directives such as RouterOutlet and RouterLink. For more information, see the forRoot() pattern section of the Singleton Services guide.


更多关于 NgModule 和路由的知识

More on NgModules and routing

你可能还对下列内容感兴趣:

You may also be interested in the following: