Angular-cli: Lazy loaded chunk not generated when lazy route is a child of non-lazy route.

Created on 2 Feb 2018  ·  99Comments  ·  Source: angular/angular-cli

Versions

Angular CLI: 1.6.6
Node: 8.9.4
OS: linux x64
Angular: 5.2.2
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router, service-worker

@angular/cdk: 5.1.0
@angular/cli: 1.6.6
@angular/material: 5.1.0
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.29
@angular-devkit/schematics: 0.0.52
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.6
@schematics/angular: 0.1.17
typescript: 2.4.2
webpack-bundle-analyzer: 2.9.2
webpack: 3.10.0

Repro steps

  • Create an angular 5 app
  • In the main root module load 2 routes by module, but not lazy loaded.
  • In one of the child modules, lazy load subsequent modules

Observed behavior

Error thrown when loading the lazy route. When search for the chunk expected in the filesystem it is not there.

Desired behavior

The lazy loaded route is loaded via a chunk create created by webpack

Mention any other details that might be useful (optional)

SO question raised, but nobody has an answer:
https://stackoverflow.com/questions/48523411/angular-5-with-angular-cli-non-lazy-loading-modules-in-the-router

Demo code of the exact issue on github:
https://github.com/jdcrecur/ang5ModuleRouting

devkibuild-angular browser more info triage #1

Most helpful comment

Actually, disregard that. I was importing my lazy-loaded module from the app's NgModule. Once I removed that import, the lazy loading worked correctly.

Perhaps the error messaging itself could be improved, regardless.

All 99 comments

I have the same issue +1

I just noticed the same issue when upgrading to angular 5.2.6 and angular/cli 1.7.1.
My lazy route is defined like

const appRoutes: Routes = [
  {
    path: 'whatever',
    loadChildren: 'app/modules/whatever/whatever.module#WhatEverModule',
    canActivate: [AuthGuard],
  }
]

And then imported within RoutingModule like RouterModule.forRoot(appRoutes).
RoutingModule is then imported in AppModule.

Until the upgrade everything was working perfectly.
Since the update the app compiles with ng serve but when I access the lazy route I get this error

core.js:1448 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
TypeError: undefined is not a function
    at Array.map (<anonymous>)
    at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:20), <anonymous>:10:34)
    at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
    at SystemJsNgModuleLoader.load (core.js:6542)
    at RouterConfigLoader.loadModuleFactory (router.js:4543)
    at RouterConfigLoader.load (router.js:4523)
...

However it still works with ng serve --aot.
So it seems to be a JIT problem.

ng -v just for a reference

Angular CLI: 1.7.1
Node: 7.10.0
OS: darwin x64
Angular: 5.2.6
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.7.1
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.1
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.6.2
webpack: 3.11.0

There is also this recent issue on stack overflow: https://stackoverflow.com/questions/48991372/angular-error-uncaught-in-promise-at-webpackasynccontext-eval-at-src

@denyo
Confirmed bug on cli 1.7.0 and 1.7.1.
Downgrading to 1.6.8 works fine.

@supergithubo thanks!
angular cli at 1.6.8 does the trick in deed.
I also tried the most recent 1.7.2. cli but the bug is still there.

+1

+1

Finally solved. Im running angular/cli ~1.7.0

the cause for me was due to the fact that in app.module, I was importing a file from a barrel that was also exporting the module i was trying to lazy load.

In all, make sure all the following are done:

  1. Remove lazy loaded module from any barrel files.
  2. Do not import lazy loaded module, using es6 import statement.
  3. Restart angular-cli app.

For some reason, I had to kill node process and restart the app before angular-cli would work.

@RyanLynnWood that did not sole the issue for me , still struggling

@RyanLynnWood is it still fixed from a cold start, and the build folder removed?

+1 still an issue with 1.7.2

Confirmed as still an issue in 1.7.2

Bug persists with 1.7.3.

Confirmed bug on cli 1.7.2.
Downgrading to 1.6.8 works fine.

Confirmed bug on CLI 1.7.3. with Angular 5.2.8
Downgrading to 1.6.8 works fine.

Confirmed bug on CLI 1.7.3. with Angular 5.2.8
Downgrading to 1.6.8 works fine.

restart ng server && work fine #

The only workaround for me is to change "loadChildren" string while --watch process running.
(CLI 1.6.8, Core and Router 5.2.8)

Angular Version: 5.2.8
Cli Version 1.7.3

Error on Lazy loading,

Console:
ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
TypeError: undefined is not a function
at Array.map ()
at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:13), :14:34)
at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
at SystemJsNgModuleLoader.load (core.js:6542)
at RouterConfigLoader.loadModuleFactory (router.js:4584)
at RouterConfigLoader.load (router.js:4564)
at eval (router.js:6981)
at PreloadAllModules.preload (router.js:6857)
at RouterPreloader.preloadConfig (router.js:6980)
at RouterPreloader.processRoutes (router.js:6959)
at Array.map ()
at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:13), :14:34)
at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
at SystemJsNgModuleLoader.load (core.js:6542)
at RouterConfigLoader.loadModuleFactory (router.js:4584)
at RouterConfigLoader.load (router.js:4564)
at eval (router.js:6981)
at PreloadAllModules.preload (router.js:6857)
at RouterPreloader.preloadConfig (router.js:6980)
at RouterPreloader.processRoutes (router.js:6959)
at resolvePromise (zone.js:809)
at eval (zone.js:861)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4740)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)

Update
I was using typescript 2.7.2, i was getting some warning for using typescript 2.7.2 so i downgraded my typescript to version 2.6.2 that error is not showing up, lazy loading is working fine

+1
Same problem here using Angular CLI 1.7.2.

I'm using ng serve --aot as a workaround

+1
same problem here using Angular Cli 1.7.3

Console:
TypeError: undefined is not a function
at Array.map ()
at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:13), :10:34)
at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
at SystemJsNgModuleLoader.load (core.js:6542)
at RouterConfigLoader.loadModuleFactory (router.js:4584)
at RouterConfigLoader.load (router.js:4564)
at MergeMapSubscriber.eval [as project] (router.js:2056)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
at Array.map ()
at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:13), :10:34)
at SystemJsNgModuleLoader.loadAndCompile (core.js:6558)
at SystemJsNgModuleLoader.load (core.js:6542)
at RouterConfigLoader.loadModuleFactory (router.js:4584)
at RouterConfigLoader.load (router.js:4564)
at MergeMapSubscriber.eval [as project] (router.js:2056)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
at resolvePromise (zone.js:809)
at resolvePromise (zone.js:775)
at eval (zone.js:858)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4740)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
at

Can confirm this is a JIT compiler issue. serve --aot works with @angular/cli 1.7.3

I also ran into this issue on 1.7.3.

Actually, disregard that. I was importing my lazy-loaded module from the app's NgModule. Once I removed that import, the lazy loading worked correctly.

Perhaps the error messaging itself could be improved, regardless.

Angular Version: 5.2.9
Cli Version 1.7.3

I have same error on Lazy loading (without --aot), it begins firing after some recompilation when ng serve running, and after that it shows always.
Restarting ng serve don't solve anything, but killing ALL node.exe from task manager helps for some period of time and everything works fine.

This seems like some issue with caching.

It seems 'ng update' with clean 'npm i' solved this problem for me. Have no idea why.

@benmalek3601 just tried reordering as you suggested. Same issue as before. only using --aot makes it compile correctly at this stage. At least for me, that is.

I also had to downgrade from 1.7.3 to 1.6.8 to work around this issue.

@cha0s solution worked for me

Angular Version: 5.2.9
Cli Version 1.7.3

@cha0s is right, duplicate import in app.module.ts and lazy loaded in app.routing.module.ts.
Just remove your lazy-loaded module in app.module.ts
and update error message please.

I now don't have any duplicates when comparing app.routing.module.ts and app.module.ts. I DID have one duplicate, removed it and did ng serve. Issue persisted. Ran ng serve --aot and the issue is gone.

@fromage9747

Basically if you are doing this

loadChildren: 'app/dashboard.module#DashboardModule'

You are already importing the module when you hit this route.

So if you import the same module (DashboardModule in this case) in app.module.ts you will get the error.

Hope this help you out.

@JoffreyHernandez Pity this wasn't my problem..... @hsuanweifu thanks for the help, I tried this, but then my catch-all route to not-found occurs for all my lazy loaded routes. I suspect to workaround that I would have to place all my separated lazy loaded routes back into the main app-routing.module.ts. Not the outcome I was after. Regardless, why on earth does --aot make it work? Anyway, hopefully, there might be some other feedback on some solutions.

I experienced the same issue with angular-cli 1.7.0 . A downgrad to 1.6.8 in package.json "devDependencies": {
"@angular/cli": "~1.6.8",
...}
solved the problem.
Of course to lazy load a module, it must be "imported" like so:
{ path: 'shop', loadChildren: './shop/shop.module#ShopModule' }
and NOT with
import { ShopModule } from './shop/shop.module'

we solved it by detach all modules from eachother and just use the loadChildren. The app also loads much faster than before.

by detach all modules from eachother

What do you mean with this ?

So is this a confirmed regression or it is an improvement in angular-cli and our apps should be fixed ? For now I pinned it to 1.6.8

Detaching was maybe the wrong word... We've removed the submodules from the import module array and let loadChildren do the work.

And it can be an inprovement, a readable error message would make it obvious

Possible solution: replace string declarations by exportable strings.
Works in my latest env (JIT and AOT)

ng -v

Angular CLI: 1.7.3
Node: 8.9.3
OS: win32 x64
Angular: 5.2.9
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cdk: 5.2.4
@angular/cli: 1.7.3
@angular/flex-layout: 5.0.0-beta.13
@angular/material: 5.2.4
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.2
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.5.3
webpack: 3.11.0

Sample

import { Routes } from '@angular/router';

export const home = 'app/features/home/home.module#HomeModule';
export const user = 'app/features/user/user.module#UserModule';

export const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'home'
  },
  {
    path: 'home',
    loadChildren: home
  },
  {
    path: 'user',
    loadChildren: user
  },
  {
    path: '**',
    redirectTo: 'home'
  }
];

@kcir3v4M Making the paths to the lazy loaded routes and the routes array exportable did not resolve the issue for me. I am not importing the lazy loaded modules in my app.module either, which I know has been the source of the problem for some. Only the downgrade to @angular/cli 1.6.8 resolves the issue for me. Seems like this is a bug that needs to be fixed by the cli team.

The solution of @kcir3v4M worked for me

The solution of @fromage9747 worked like a charm

core.js:1448 ERROR Error: Uncaught (in promise): TypeError: undefined is not a function
TypeError: undefined is not a function
    at Array.map (<anonymous>)
    at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:13), <anonymous>:22:34)
    at SystemJsNgModuleLoader.loadFactory (core.js:6578)
    at SystemJsNgModuleLoader.load (core.js:6542)
    at RouterConfigLoader.loadModuleFactory (router.js:4589)
    at RouterConfigLoader.load (router.js:4569)
    at MergeMapSubscriber.eval [as project] (router.js:2061)
    at MergeMapSubscriber._tryNext (mergeMap.js:128)
    at MergeMapSubscriber._next (mergeMap.js:118)
    at MergeMapSubscriber.Subscriber.next (Subscriber.js:95)
    at Array.map (<anonymous>)
    at webpackAsyncContext (eval at ./src/$$_lazy_route_resource lazy recursive (main.bundle.js:13), <anonymous>:22:34)
    at SystemJsNgModuleLoader.loadFactory (core.js:6578)
    at SystemJsNgModuleLoader.load (core.js:6542)
    at RouterConfigLoader.loadModuleFactory (router.js:4589)
    at RouterConfigLoader.load (router.js:4569)
    at MergeMapSubscriber.eval [as project] (router.js:2061)
    at MergeMapSubscriber._tryNext (mergeMap.js:128)
    at MergeMapSubscriber._next (mergeMap.js:118)
    at MergeMapSubscriber.Subscriber.next (Subscriber.js:95)
    at resolvePromise (zone.js:814)
    at resolvePromise (zone.js:771)
    at eval (zone.js:873)
    at ZoneDelegate.invokeTask (zone.js:421)
    at Object.onInvokeTask (core.js:4740)
    at ZoneDelegate.invokeTask (zone.js:420)
    at Zone.runTask (zone.js:188)
    at drainMicroTaskQueue (zone.js:595)

@kcir3v4M Thank you, is solved

The solution of @kcir3v4M worked for me, Thank you :)

Just check if you have the lazy module imported into the app.module, remove it and restart ng serve.
It will word like charm!!!

@aiherrera it doesn't help for many of us.

I tried all of the suggested solutions. The only thing that fixes this issue for me is using "ng serve -aot".

Ok, after restarting my OS, it looks like that "ng serve" is also working after removing the import of the lazy loaded modules from the app module.

@icanit Your solution worked for me.. Killed all node.exe and then open new terminal and issue ng --serve everything is good again....

In addition to exporting the lazy paths as @kcir3v4M described we had one more thing to change.
We were exporting the lazy module in a barrel file. Although the lazy path in the route pointed to the module itself and not the barrel we had to remove the export in order to make ng serve (jit) work. ng serve --aot didn't mind.

@TobiasMalikowski perhaps this helps you.

@foote-Greg, @icanit yeah, it also works for me.

dear ng team. this b.s. cost me half a day

is that against the rules?

Also encountering this...

anyone know why ng serve --aot as workaround works, but ng serve is not?

Angular CLI: 6.0.1
Node: 8.11.1
Angular: 6.0.1/6.0.2

Initially, I got this error message:
Error: Uncaught (in promise): TypeError: undefined is not a function TypeError: undefined is not a function

I tried several approaches mentioned here, but so far none worked, for example the one by @kcir3v4M

export const wizard = 'app/project-wizard/project-wizard.module#ProjectWizardModule';
With this, I get
Uncaught (in promise): Error: Cannot find module "app/project-wizard/project-wizard.module". Error: Cannot find module "app/project-wizard/project-wizard.module".

I also tried it with ./ instead of app.
I also reverted back to CLI 1.6.8, but still no success.

I finally got it working with this solution:

import { ProjectWizardModule } from './project-wizard/project-wizard.module';

{
        path: 'wizard',
        loadChildren: () => ProjectWizardModule
 },

Another workaround:

export function loadWizardModule() { return ProjectWizardModule }

{
        path: 'wizard',
        loadChildren: loadWizardModule
}

These workarounds might work for you - but they are not lazy-loading.

@matthiassommer, you saved my day!! It worked for me. Thank you!! :)

In other tickers for the same problem it has been explained that this won't be AOT compiled. For me the best workaround for now is to use ng serve --aot

there's definitely some caching/watching issue too. sometimes i bite it and ctrl+C and re-serve... definitely seen different behaviour doing this

While @matthiassommer's solution might fix the recompile error, it defeats the purpose of lazy loading. You are importing all modules while defining your routes so all those modules will have to be loaded at the beginning instead of lazy-loaded when necessary during navigation.

@martin-g In my case it also only works with ng serve --aot. Will it always be like this?

@lucasalmeida8 Hopefully it will be fixed one day!

this doesn't work in the main.ts:

`let platform = platformBrowserDynamic();

if (environment.production) {
fetch('/config/get').then(response => {
response.json().then(result => {
Globals.Configuration = result;

        platform.bootstrapModule(AppModule)
            .catch(err => console.log(err));
    });
});

} else {
Globals.Configuration = {
apiUrl: environment.ApiUrl,
};

platform.bootstrapModule(AppModule)
    .catch(err => console.log(err));

}
`

this does:
`let platform = platformBrowserDynamic();

//if (environment.production) {
fetch('/config/get').then(response => {
response.json().then(result => {
Globals.Configuration = result;

    platform.bootstrapModule(AppModule)
        .catch(err => console.log(err));
});

});`

Note that the if statement is commented out.

This is Angular 6.0.2 cli or 6.0.3 cli.

It will also fail if you put in an error catch too on the fetch.

This however does work:

`if (environment.production) {
fetch('/config/get').then(response => {
response.json().then(result => {
Globals.Configuration = result;

        bootstrap();
    });
});

} else {
Globals.Configuration = {
apiUrl: environment.ApiUrl,
blobUrl: environment.blobUrl,
logoUrl: environment.LogoUrl,
site: environment.site,
useGoogleAnalytics: environment.UseGoogleAnalytics
};

bootstrap();

}

function bootstrap() {
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
}
`

So based on that, someone is doing some hackery and if it sees more than one boostrapModule call in main.ts it freaks out and doesn't build them properly. As long as there is just one and only one bootstrapModule call it's fine.

In my case (Angular version 5.2) there was a bad order in app.module.ts. As documentation said: You have to import AppRoutingModule at the end and feature modules above.
Example:
imports: [
BrowserModule,
FormsModule,
HeroesModule,
AppRoutingModule
]
Here is link for more details:
https://angular.io/guide/router#module-import-order-matters

+1

The order is not the problem. We use angular 6.03 and angular/cli 6.07 and have the same problem. The problem is the always new versions with webpack. They are just not tested properly before they are released.

I just arrived at this after fighting with my code for about 8 hours trying to work out why it was giving me mat-toolbar not defined issues when I had already reverted the component in question to the default "something works"...

Angular CLI: 6.0.8
Node: 8.11.2
OS: win32 x64
Angular: 6.0.5

@matthiassommer Thank you. Your solution worked for me. I had encountered the same error as you (Error: Cannot find module...) when trying @kcir3v4M's fix.

ng -v
Angular CLI: 6.0.8
Node: 9.8.0
OS: darwin x64
Angular: 6.0.0

thxs @matthiassommer work for me 😄

@matthiassommer,new way,thx

well, it work fine with ng serve on version 1.7.4, but it doesn´t work with ng build --prod

work fine with:

...
 export function loadComponentModule() { return ComponentModule; }
...

{ path: 'foo', loadChildren: loadComponentModule },

I get this error in a related, but chicken-egg situation, which is this:

I depend on a 3rd party library (angular2-token) that is a service (so you need to provide it in app.module) and a guard (that I apply in a lazy route). For example:

app.routing.ts

import { Angular2TokenService } from 'angular2-token';

export const routes: Routes = [
  { path: '', redirectTo: 'pages', pathMatch: 'full' },
  { path: 'pages', loadChildren: 'app/pages/pages.module#PagesModule', 
      canActivate: [Angular2TokenService] },
]

app.module.ts

import { Angular2TokenService } from 'angular2-token';
...other imports...

@NgModule({
  declarations: [
    AppComponent,
   ...other components...
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ModalModule.forRoot(),
   ...other modules...
    routing
  ],
  providers: [
    AppConfig, 
    Angular2TokenService,
    UserService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Clearly the same module (angluar2-token) is imported in both app.routing and app.module, which causes this error. But obviously I cannot remove it from app.module, as it provides a service that needs to be available globally (otherwise you get no provider error).

This worked perfectly fine in Angular4 and whatever cli version I had then (1.0.0 maybe). But

  • With Angular 5, it does not work with cli 1.7.4, unless I do ng serve --aot
  • With Angular 5, it does work with cli 1.6.8 and ng serve
ngular CLI: 1.7.4
Node: 8.10.0
OS: darwin x64
Angular: 5.2.11
... animations, common, compiler, compiler-cli, core, forms
... http, platform-browser, platform-browser-dynamic
... platform-server, router

@angular/cli: 1.7.4
@angular/language-service: 4.3.4
@angular-devkit/build-optimizer: 0.3.2
@angular-devkit/core: 0.3.2
@angular-devkit/schematics: 0.3.2
@ngtools/json-schema: 1.2.0
@ngtools/webpack: 1.10.2
@schematics/angular: 0.3.2
@schematics/package-update: 0.3.2
typescript: 2.4.2
webpack: 3.11.0

UPDATE
I got this scenario to work using 1.7.4 and ng serve.

  1. Deleted node_modules folder and package.lock.json and then npm install
  2. Closed terminal window
  3. Opened new terminal window
  4. PUT BACK the node_modules folder and lock file (ie BACK FROM TRASH)

Clearly some kind of caching issue as someone suggested before.

Thanks @matthiassommer , worked for me without any compilation error by doing :

export function loadSessionStageModule() {
  return SessionStageModule
}

export function loadManageEvaluationModule() {
  return ManageEvaluationModule
}

export const routes: Routes = [
  {
    path: '',
    component: FullLayoutComponent,
    children: [
      {
        path: 'session-stage',
        loadChildren: loadSessionStageModule
      },
      {
        path: 'manage-evaluation',
        loadChildren: loadManageEvaluationModule
      }

    ],
  },
  {
    path: 'login',
    component: LoginComponent
  }
];

Angular CLI: 6.0.8
Node: 8.9.4
Angular: 6.0.7

my lazy module was hiddenly imported through index.ts. Once removed works fine without aot

@AbbeYassine your example is not a lazy loaded module in the first place. Lazy loading is not whenever you use loadChildren, but only when the value of loadChildren is a string that is an import path to a module, like: loadChildren: 'app/pages/pages.module#PagesModule' in https://github.com/angular/angular-cli/issues/9488#issuecomment-402282704

@matthiassommer when you use lambda expression, it's not lazy loaded

@kcir3v4M works for me. angular cli 1.7.3

hi every one i can try to solve the issue if you share the project structure and modules code.
its just related to calling components and modules in wrong way

@jdcrecur i have solved you issue in repo

@kcir3v4M Your solution worked for me with the latest CLI. I think removing the modules from the app module makes sense when they are lazy loaded but yours is easier and with less impact for me. Thank you!

@matthiassommer Your solution worked for me.

I had:

{ path: 'dashboard', loadChildren: './components/core/core.module#CoreModule' },

Changed it to:

{ path: 'dashboard', loadChildren: () => CoreModule},

No more errors and the navigation works as its supposed wo without using --aot.

Thank you!

Edit:

After this I then tried to do a ng build --prod and received this error:

ERROR in Error during template compile of 'AppRoutingModule'
  Function expressions are not supported in decorators in 'ɵ0'
    'ɵ0' contains the error at app/app-routing.module.ts(26,38)
      Consider changing the function expression into an exported function.

I then needed to make use of @matthiassommer second workaround.

import { CoreModule } from './components/core/core.module';

export function loadCoreModule() { return CoreModule; }
{ path: 'dashboard', loadChildren: loadCoreModule},



md5-e123f670f9f9c09ce8670a5de4ba0c49



Runtime compiler is not loaded
Error: Runtime compiler is not loaded

Actually, disregard that. I was importing my lazy-loaded module from the app's NgModule. Once I removed that import, the lazy loading worked correctly.

Perhaps the error messaging itself could be improved, regardless.

It works..!!

Finally solved. Im running angular/cli ~1.7.0

the cause for me was due to the fact that in app.module, I was importing a file from a barrel that was also exporting the module i was trying to lazy load.

In all, make sure all the following are done:

  1. Remove lazy loaded module from any barrel files.
  2. Do not import lazy loaded module, using es6 import statement.
  3. Restart angular-cli app.

For some reason, I had to kill node process and restart the app before angular-cli would work.

Fixed for me too. Potential workaround could be pointing to the router module directly.

Solved for me:
I changed base href="./" to base href="/" in my index.html

The most likely cause for this problem is described by @cha0s in https://github.com/angular/angular-cli/issues/9488#issuecomment-374037802:

Actually, disregard that. I was importing my lazy-loaded module from the app's NgModule. Once I removed that import, the lazy loading worked correctly.
Perhaps the error messaging itself could be improved, regardless.

A lazy route should only be referenced by the loadChildren string and never by an import statement. We should show a better error for this.

If you have other cases where you are getting such errors please let me know, preferably with a reproduction.

I solved this issue by removing the the lazy loaded module from an other featured module and setting loadchildren:'src/app/products.module#ProductsModule'. There should be no importing reference of lazy loaded module else where in other featured modules.

I tried everything.

  • "@angular/core": "~7.2.0",
  • "@angular/cli": "~7.3.1",

For me working only this:

Main routing: app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'TestLazy',       
    // <== Without 'component: xxxxxxx' and without import component and TestModule above !!!
    loadChildren: './TestLazy/test.module#TestModule'
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Test.module with routing. Only here are import lazy components. And Children patch it's separate. Not like children: [ .... ]

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TestLazy2Component } from './TestLazy2/TestLazy2.component';
import { TestLazyComponent } from './TestLazy.component';


const routes: Routes = [
  {
    path: '',
    component: TestLazyComponent,
  },
  {
    path: 'TestLazy2',
    component: TestLazy2Component
  }
];

@NgModule({
  declarations: [
    TestLazyComponent,
    TestLazy2Component
  ],

  imports: [RouterModule.forChild(routes)

  ],
  exports: [

  ]
})
export class TestModule {}

in html full path

 <li>
      <a   [routerLink]="['/TestLazy']" >Lazy Load 1</a>
  </li>
  <li>
    <a [routerLink]="['/TestLazy/TestLazy2']">Lazy Load 2</a>  // <== patch
  </li>

Is this the correct lazyLoading ?? It does not matter if I click first link "TestLazy" or "TestLazy2" - is loaded "TestLazy-test-module-ngfactory.js" :)

And app.module also does not contain anything

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AuthService } from './_services/auth.service';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule
   ],
   providers: [
      AuthService
   ],
   bootstrap: [
      AppComponent
   ]
})
export class AppModule { }

Actually, disregard that. I was importing my lazy-loaded module from the app's NgModule. Once I removed that import, the lazy loading worked correctly.

Perhaps the error messaging itself could be improved, regardless.

Oh my god! after several hours you help me out with your response!!! Thank you!

Hi @filipesilva ,
I have strange issue, lazy loading doesn't work. It really drives me crazy.
Please take a look this, I don't know what I missed, or this is a bug.

"dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular/animations": "^7.2.15",
    "@angular/cdk": "^7.3.7",
    "@angular/common": "^7.2.15",
    "@angular/compiler": "^7.2.15",
    "@angular/core": "^7.2.15",
    "@angular/flex-layout": "7.0.0-beta.22",
    "@angular/forms": "^7.2.15",
    "@angular/http": "^7.2.15",
    "@angular/material": "^7.3.7",
    "@angular/material-moment-adapter": "^7.3.7",
    "@angular/platform-browser": "^7.2.15",
    "@angular/platform-browser-dynamic": "^7.2.15",
    "@angular/router": "^7.2.15",
    "@ngrx/effects": "^7.4.0",
    "@ngrx/router-store": "^7.4.0",
    "@ngrx/store": "^7.4.0",
    "@ngrx/store-devtools": "^7.4.0",
    "@ngx-translate/core": "^11.0.1",
    "@swimlane/ngx-charts": "^10.1.0",
    "@swimlane/ngx-datatable": "^14.0.0",
    "@swimlane/ngx-dnd": "^7.0.0",
    "@types/date-fns": "^2.6.0",
    "angular-calendar": "^0.27.7",
    "angular-in-memory-web-api": "^0.8.0",
    "angular2-markdown": "^2.2.3",
    "classlist.js": "^1.1.20150312",
    "core-js": "^3.0.1",
    "d3": "^5.9.2",
    "date-fns": "^1.30.1",
    "file-saver": "^2.0.1",
    "hammerjs": "^2.0.8",
    "highlight.js": "^9.15.6",
    "intl": "^1.2.5",
    "moment": "^2.24.0",
    "ngrx-store-freeze": "^0.2.4",
    "ngx-color-picker": "^7.5.0",
    "ngx-cookie-service": "^2.1.0",
    "ngx-drag-drop": "^2.0.0-rc.6",
    "ngx-infinite-scroll": "^7.1.0",
    "perfect-scrollbar": "^1.4.0",
    "primeng": "^7.1.2",
    "rxjs": "^6.5.1",
    "rxjs-compat": "^6.5.1",
    "tslib": "^1.9.0",
    "web-animations-js": "2.3.1",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.9",
    "@angular/cli": "^7.3.9",
    "@angular/compiler-cli": "^7.2.15",
    "@angular/language-service": "^7.2.15",
    "@angularclass/hmr": "^2.1.3",
    "@types/file-saver": "^2.0.0",
    "@types/jasmine": "^3.3.12",
    "@types/jasminewd2": "^2.0.6",
    "@types/node": "^12.0.0",
    "codelyzer": "^5.0.1",
    "jasmine-core": "^3.4.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.1.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "^2.0.5",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "protractor": "^5.4.2",
    "ts-node": "^8.1.0",
    "tslint": "^5.16.0",
    "typescript": "3.2.4"
  }

@filipesilva , I solved the problem.

[IMPORTANT NOTICE]

"skipTemplateCodegen": true option prevents Angular 7 to build lazy loading modules, but lazy loading modules works in Angular 5 with this option.

Finally solved. Im running angular/cli ~1.7.0

the cause for me was due to the fact that in app.module, I was importing a file from a barrel that was also exporting the module i was trying to lazy load.

In all, make sure all the following are done:

  1. Remove lazy loaded module from any barrel files.
  2. Do not import lazy loaded module, using es6 import statement.
  3. Restart angular-cli app.

For some reason, I had to kill node process and restart the app before angular-cli would work.

I forgot to remove the Module from app.modules 🤦‍♂️ dont be like me

Is this still a problem that people are experiencing with recent Angular CLI versions?

Yes I am still having this issue .

I was having this issue with angular-cli 8.1.3, with the (not ideal) workaround to touch app-routing.module.ts while ng-serving the app, but solved it thanks to https://github.com/angular/angular-cli/issues/10673#issuecomment-473901065 . I had a non-exported class in my app.module.ts, and exporting it solved the issue. Dunno if that's supposed to be normal, as ES modules are mostly black magic to me.

Before finding that solution, I had tracked the problem down to the generated main.js. After launching the command ng build --watch, the beginning of that file was the following, and the angular app was not starting:

(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["main"],{

/***/ "./$$_lazy_route_resource lazy recursive":
/*!******************************************************!*\
  !*** ./$$_lazy_route_resource lazy namespace object ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports) {

function webpackEmptyAsyncContext(req) {
        // Here Promise.resolve().then() is used instead of new Promise() to prevent

After touching the file app-routing.module.ts , the beginning of main.js became the following (and the error was gone):

(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["main"],{

/***/ "./$$_lazy_route_resource lazy recursive":
/*!******************************************************!*\
  !*** ./$$_lazy_route_resource lazy namespace object ***!
  \******************************************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

var map = {
        "./login/login.module": [
                "./src/app/login/login.module.ts",
                "login-login-module"
        ],
        "./task-process/task-process.module": [
                "./src/app/task-process/task-process.module.ts",
                "default~task-process-task-process-module~tasks-list-tasks-list-module",
                "task-process-task-process-module"
        ],
        "./tasks-list/tasks-list.module": [
                "./src/app/tasks-list/tasks-list.module.ts",
                "default~task-process-task-process-module~tasks-list-tasks-list-module",
                "tasks-list-tasks-list-module"
        ]
};
function webpackAsyncContext(req) {
        if(!__webpack_require__.o(map, req))

please do not import modules (lazy modules) in app.module.ts file

it'll reduce main.js file size and generates chunks as well

@alan-agius4 Is there any more info on this ? Recently migrated to angular 7 . Lazy loading compilation in chunks is not happening for me . I have got typescripts errors as well , but that should not be linked to lazy loading compilation right ?

@alan-agius4 Is there any more info on this ? Recently migrated to angular 7 . Lazy loading compilation in chunks is not happening for me . I have got typescripts errors as well , but that should not be linked to lazy loading compilation right ?

I would clean the project if i were you. also put namedChunks on in the build to see if they are building correctly

@ricardosaracino Thanks . I observed an issue right now after hours of debugging . The same issue was mentioned by @ceyhunn here in this exact thread : https://github.com/angular/angular/issues/27023#issuecomment-491206139 .

When I first try ng serve, I just get 6 chunks : main.js, polyfills.js, runtime.js, scripts.js, styles.js and vendor.js along with various typescript errors (I am okay with typescript errors since they are coming up as typescript has been updated from 2.4 to 3.1 and according to me they are expected and can be resolved) . What's strange is : as per @ceyhunn when I now go to the app.module.ts, where my routes are mentioned and just try : CONTROL+S by introducing some blank characters using backspace , then all the lazy loading named chunks start showing up in the terminal . I had opened an issue regarding that earlier : https://github.com/angular/angular-cli/issues/19092 which basically explains my situation with screen shots .

Do you @ricardosaracino or @ceyhunn have any idea as to what is causing this strange behavior and how it can be resolved ?

one thing to note and im not etirely sure when it was introduced is that angular started to use a angular.json file. this might be the cause of some problems.

image

image

@ricardosaracino Agreed . However I already have the angular.json file . They introduced it in angular 6 . So when I migrated the project from angular 4 to 7 , my angular-cli.json got converted into angular.json automatically .

There seems to be multiple reported issues in here which is hard to follow and hard to answer.

That said, the original reported here should not longer be reproducible in newer versions of the Angular CLI. Please update to the most recent Angular CLI version.

If the problem persists after upgrading, please open a new issue, provide a simple repository reproducing the problem, and describe the difference between the expected and current behavior.

Important to point out that Angular versions prior to 8 are no longer supported and version 8 is currently in LTS which support will terminate on the Nov 28, 2020. See https://angular.io/guide/releases#support-policy-and-schedule for more information.

Was this page helpful?
0 / 5 - 0 ratings