当项目比较小的时候可以不用自定义模块,但是当项目非常庞大的时候,可以使用自定义模块来组织项目,并通过 angular 自定义模块实现路由的懒加载
自定义模块
# 创建 user 模块
ng g module modules/user
# 创建 user 模块下的子组件
ng g component modules/user/components/fun
ng g component modules/user/components/news
# 创建 user 模块的组件
ng g component modules/user
- user 模块 user.module.ts
@NgModule({
declarations: [NewsComponent, FunComponent, UserComponent],
// 暴露出自定义模块的组件,未暴露的组件在根模块无法直接使用
// 但是可以在当前 user 模块使用
exports: [UserComponent, NewsComponent],
imports: [
CommonModule,
],
})
- 使用 user.component.html
<p>
user works!
</p>
<app-fun></app-fun>
<app-news></app-news>
- 根模块 app.module.ts
// 引入自定义模块
import { UserModule } from './modules/user/user.module'
imports: [
UserModule,
],
- 使用 app.component.html
<app-user></app-user>
<app-news></app-news>
<!--<app-fun></app-fun> 未在模块暴露出去,使用会报错-->
配置路由模块懒加载
# 创建带有路由的模块
ng g module modules/lazy --routing
# 创建 user 模块下的子组件
ng g component modules/lazy/components/bar
ng g component modules/lazy/components/foo
# 创建 user 模块的组件
ng g component modules/lazy
- 配置路由 password-routing.module.ts
// 引入当前模块的组件
import { LazyComponent } from './lazy.component'
const routes: Routes = [
{ path: '', component: LazyComponent },
]
- 根模块配置路由 app-routing.module.ts
const routes: Routes = [
{
path: 'lazy',
loadChildren: './modules/lazy/lazy.module#LazyModule',
},
]
- 使用 app.component.html
<a routerLink="/lazy">lazy</a>