MST
星途 面试题库

面试题:Angular中懒加载模块的基本配置

在Angular项目里,如何配置一个模块实现懒加载?请简要说明相关配置步骤及涉及到的关键代码。
22.7万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 创建懒加载模块
    • 使用Angular CLI命令创建一个新模块,例如:ng generate module lazy - - route lazy - - module app.module。这里lazy是模块名,--route指定路由路径,--module指定该懒加载模块属于哪个根模块。
  2. 配置路由
    • 在懒加载模块的路由文件(如lazy - routing.module.ts)中配置该模块的路由。例如:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: '',
    component: // 这里填写该模块默认展示的组件
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LazyRoutingModule { }
  1. 在主路由模块中配置懒加载
    • 在主路由模块(如app - routing.module.ts)中,将懒加载模块配置为路由的loadChildren。例如:
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)
  }
];

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

关键代码总结:

  • 懒加载模块路由文件RouterModule.forChild(routes)用于配置子路由。
  • 主路由模块loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule)使用动态导入实现懒加载,只有在访问到/lazy路径时才会加载LazyModule模块。