Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ??

like image 312
firasKoubaa Avatar asked Mar 01 '18 16:03

firasKoubaa


1 Answers

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.

like image 60
Frank Adrian Avatar answered Oct 12 '22 23:10

Frank Adrian