angularlazy-loadingangular-aot

Angular 8 lazy loading routes from custom library broken at runtime when project build with AOT


I was intent to access some lazy-loaded routes defined in a custom extended library. Everything was alright until I'm wanted to build a production package (AOT active). The build passed, but when I'm trying to reach a route I get this error in the browser's console :

Uncaught Error: Uncaught (in promise): Error: Runtime compiler is not loaded
Error: Runtime compiler is not loaded
at e.Jr (main.41ff3398f5c3f189c836.js:1)
at t.project (main.41ff3398f5c3f189c836.js:1)
at t._tryNext (main.41ff3398f5c3f189c836.js:1)
... 

I assume that it's related with loadChildren attribute, when I build the lib, ng-packgr failed with new Angular 8 lazy-loading synthaxe, arrow function (it's a known issue https://github.com/ng-packagr/ng-packagr/issues/1285).

Lazy Routes are defined in the custom library like this :

export function getRouteModule() {
  return RouteModule;
}
export const MAIN_APP_ROUTES: Routes = [
{
  path: 'route',
  loadChildren: getRouteModule
},
...
];

Then in my consumer project :

@NgModule({
 imports: [
     BrowserModule,
     LibraryModule,
     RouterModule.forRoot(MAIN_APP_ROUTES, {useHash: true})
 ],
 declarations: [
     AppComponent
 ],
 bootstrap: [AppComponent]
 })
 export class AppModule {
 }

so I tried several synthaxes, the older one combined with Angular library should be great :

{
  path: 'route',
  loadChildren: '@MyLib/route/route.module#RouteModule'
},
...

but it doesn't worked.

Any idea ?


Solution

  • As I find earlier in this discussion : https://github.com/angular/angular-cli/issues/6373#issuecomment-453006158

    It's not recommanded to manage lazy-loaded module inside an Angular library because it's doesn't realy supported by ng packagr. Moreover, there is a way around this problem. It's possible to use module wrapper as it's explained in this tutorial : https://medium.com/@tomastrajan/why-and-how-to-lazy-load-angular-libraries-a3bf1489fe24

    First you have to define a Module in your application that will wrap a module from the library :

    import { NgModule } from '@angular/core';
    import {RouteModule} from '@MyLib';
    
    @NgModule({
      declarations: [],
      imports: [
       RouteModule
      ]
    })
    export class RouteWrapperModule { }
    

    Then define the routes like this in your App :

    import {Routes} from '@angular/router';
    
    const routes: Routes = [
     // other routes
     {
      path: 'route',
      loadChildren: 'someWhereInTheMainApp/route-wrapper.module#RouteWrapperModule'
     }
    ];
    

    It'll solve the bug with AOT on runtime.