Angular 5:使用Angular-CLI 1.7.x进行ng build - -prod时,Lazy Loading无法正常工作

fir*_*baa 6 javascript typescript angular2-routing angular-cli angular

我在工作:

  • Angular:5.2.6
  • Angular-CLI:1.7.x

我在我的应用程序下有这个路由文件(我有一些延迟加载模块):

const homeRoutes: Routes = [
  {
    path: 'home', component: HomeComponent,
    children: [
        ....
      {
        path: 'admin',
        loadChildren: 'app/home/admin/admin.module#AdminModule',
        canActivate: [AuthGuardAdmin]
      },
    ]
  },
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(homeRoutes)
  ],
  exports: [
    RouterModule
  ],
  declarations: []
})
export class HomeRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

运行ng服务,延迟加载不起作用,我得到这个错误:

>     core.js:1448 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
>     TypeError: undefined is not a function
Run Code Online (Sandbox Code Playgroud)

有些谷歌搜索我被告知改变我的懒加载像这样:

  {
    path: 'admin',
    loadChildren: ()=> AdminModule,
    canActivate: [AuthGuardAdmin]
  },
Run Code Online (Sandbox Code Playgroud)

这适用于开发模式 :) ,但是当运行ng build --prod时,它会再次失败:

ERROR in Error during template compile of 'HomeRoutingModule'
  Function expressions are not supported in decorators in '?0'
    '?0' contains the error at app/home/home-routing/home-routing.module.ts(182,23)
      Consider changing the function expression into an exported function.
Run Code Online (Sandbox Code Playgroud)

所以我担心我无法让它发挥作用.

由于其他一些原因,我不想将angular-cli降级到1.6.x.

所以任何想法如何解决?

Fra*_*ian 2

解决方案是非常明显的。

对我来说,它是删除 app.module 中的延迟加载模块导入。因为它应该是延迟加载的,所以这是有道理的。在此线程中的某处找到了此问题的解决方案:https://github.com/angular/angular-cli/issues/9488 适用于 cli 版本 > 1.7.x

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule,
    // custom modules
    AppRoutingModule,
    HeaderModule,
    LoginModule,
    Feature1Module, <!-- this is my lazyLoaded module // remove this line
    ConceptModule
  ],
  providers: [AuthService, AuthStoreService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule {
}
Run Code Online (Sandbox Code Playgroud)

希望它对其他人有帮助。