简体   繁体   中英

Angular 5 : Lazy Loading is not working properly with ng build - -prod with Angular-CLI 1.7.x

I'm working under :

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

I have this routing file under my app (where i ve some lazy loading modules ) :

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 { }

Whle running ng serve , the lazy loading did not work , and i get this error :

>     core.js:1448 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
>     TypeError: undefined is not a function

Whith some googling i was told to change my lazy loading like this :

  {
    path: 'admin',
    loadChildren: ()=> AdminModule,
    canActivate: [AuthGuardAdmin]
  },

this works in development mode :) , but when running ng build --prod , it fails again throwing this :

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.

So i'm afraid that i'm not able to get it work.

I don t want to downgrade angular-cli to 1.6.x for some other reasons .

So any ideas of how to fix it ??

The solution is quite apparent.

For me it was to remove the lazy loaded module import in app.module. Since it should be lazy loaded this makes sense. Found the solution to this somewhere in this thread: https://github.com/angular/angular-cli/issues/9488 Works with cli version > 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 {
}

Hope it helps someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM