Angular带回调函数的懒加载在AoT模式下编译失败
解决Angular生产构建中“expressions are not supported in decorators in 'ɵ0'”错误
我之前用ng build --prod --build-optimizer打包Angular测试SPA时,也碰到过一模一样的错误:"expressions are not supported in decorators in 'ɵ0' angular loadchild"。这个问题的核心是Angular生产构建默认启用的AOT编译,对装饰器里的表达式有严格限制,你当前的loadChildren写法刚好触发了这个限制。
先看你原来的路由代码:
import {MainModule} from './../../main/main.module'; const sidenavRoutes: Routes = [ { path: '', component: SidenavComponent, canActivateChild: [AuthGuard], children: [ { path: '', loadChildren: () =>MainModule} ] }, ];
这里的() => MainModule是直接在路由装饰器的上下文里返回模块类,AOT编译无法静态解析这种表达式。你只需要把loadChildren改成Angular官方推荐的动态导入形式(Angular 9及以上版本适用),或者字符串路径形式(兼容旧版本)就能解决问题:
修改后的代码(Angular 9+推荐)
const sidenavRoutes: Routes = [ { path: '', component: SidenavComponent, canActivateChild: [AuthGuard], children: [ { path: '', loadChildren: () => import('./../../main/main.module').then(m => m.MainModule) } ] }, ];
兼容Angular 8及以下版本的写法
const sidenavRoutes: Routes = [ { path: '', component: SidenavComponent, canActivateChild: [AuthGuard], children: [ { path: '', loadChildren: '../../main/main.module#MainModule' } ] }, ];
这样修改后,AOT编译就能正确识别模块的加载路径,再执行ng build --prod --build-optimizer就不会再出现那个错误了。
内容的提问来源于stack exchange,提问作者ALGDB
相关产品推荐
相关产品推荐

