59

I was trying to find any solution for this error but nothing works for me. I have simple Angular2 App created with Angular-CLI. When I serve this app in browser I'm getting this error: EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'. I was trying using different path in loadChildren:

'/app/test.module'
'./app/test.module'
'./test.module'
'/src/app/test.module'

Folders

src/
  app/
    app-routing.module.ts
    app.component.ts
    app.module.ts
    test.component.ts
    test.module.ts

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { RoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app-routing.module.ts

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


const routes: Routes = [
  { path: '', loadChildren: '/app/test.module' }
];

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

test.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';

export const routes: Routes = [
    { path: '', component: TestComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  exports: [TestComponent],
  declarations: [TestComponent]
})
export default class TestModule { }

stack trace

        error_handler.js:45EXCEPTION: Uncaught (in promise): Error: Cannot find module '/app/test.module'.ErrorHandler.handleError @ error_handler.js:45next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.612 error_handler.js:50ORIGINAL STACKTRACE:ErrorHandler.handleError @ error_handler.js:50next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.613 error_handler.js:51Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.
        at resolvePromise (zone.js:429)
        at zone.js:406
        at ZoneDelegate.invoke (zone.js:203)
        at Object.onInvoke (ng_zone_impl.js:43)
        at ZoneDelegate.invoke (zone.js:202)
        at Zone.run (zone.js:96)
        at zone.js:462
        at ZoneDelegate.invokeTask (zone.js:236)
        at Object.onInvokeTask (ng_zone_impl.js:34)
        at ZoneDelegate.invokeTask (zone.js:235)ErrorHandler.handleError @ error_handler.js:51next @ application_ref.js:273schedulerFn @ async.js:82SafeSubscriber.__tryOrUnsub @ Subscriber.js:223SafeSubscriber.next @ Subscriber.js:172Subscriber._next @ Subscriber.js:125Subscriber.next @ Subscriber.js:89Subject.next @ Subject.js:55EventEmitter.emit @ async.js:74onError @ ng_zone.js:120onHandleError @ ng_zone_impl.js:64ZoneDelegate.handleError @ zone.js:207Zone.runGuarded @ zone.js:113_loop_1 @ zone.js:379drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.614 zone.js:355Unhandled Promise rejection: Cannot find module '/app/test.module'. ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot find module '/app/test.module'.(…) Error: Cannot find module '/app/test.module'.
        at webpackEmptyContext (http://localhost:4200/main.bundle.js:49550:8)
        at SystemJsNgModuleLoader.loadAndCompile (http://localhost:4200/main.bundle.js:57952:40)
        at SystemJsNgModuleLoader.load (http://localhost:4200/main.bundle.js:57945:60)
        at RouterConfigLoader.loadModuleFactory (http://localhost:4200/main.bundle.js:22354:128)
        at RouterConfigLoader.load (http://localhost:4200/main.bundle.js:22346:81)
        at MergeMapSubscriber.project (http://localhost:4200/main.bundle.js:61105:111)
        at MergeMapSubscriber._tryNext (http://localhost:4200/main.bundle.js:32515:27)
        at MergeMapSubscriber._next (http://localhost:4200/main.bundle.js:32505:18)
        at MergeMapSubscriber.Subscriber.next (http://localhost:4200/main.bundle.js:7085:18)
        at ScalarObservable._subscribe (http://localhost:4200/main.bundle.js:48555:24)consoleError @ zone.js:355_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
    2016-10-08 14:22:50.620 zone.js:357Error: Uncaught (in promise): Error: Cannot find module '/app/test.module'.(…)consoleError @ zone.js:357_loop_1 @ zone.js:382drainMicroTaskQueue @ zone.js:386
Eli
  • 979
  • 8
  • 19
arthurr
  • 1,075
  • 1
  • 10
  • 19
  • 1
    try `loadChildren: '/app/test.module'` to change to `loadChildren: 'app/test.module'` This will work I guess. – micronyks Oct 08 '16 at 13:44
  • I tried this before but had the same error – arthurr Oct 08 '16 at 14:09
  • 12
    I was troubled by this error all night. At last, I found I just need to stop the `ng serve` command, and restart. Then the error gone. Because the module will be lazy loaded, maybe there is some work will be done during starting test server. – Mavlarn Nov 08 '16 at 16:02
  • @Mavlarn restart ng serve work for me as well, thanks ! – moyomeh Nov 11 '16 at 17:27
  • 1
    @arthurr did you use `ng build --aot ` for compilation? cause I get this error only while doing --aot, otherwise it works fine – Nikhil Radadiya Nov 06 '17 at 13:21
  • @NikhilRadadiya yes, I'm using -aot and I don't have this error any more. For me solution was to restart `ng serve` after adding new module to routes. – arthurr Nov 20 '17 at 15:24
  • @arthurr I also got it work, for me the problem was `ngBusy` that dep. don't support `--aot` with lazy-loading – Nikhil Radadiya Nov 21 '17 at 08:03

15 Answers15

69

restarting ng serve worked for me

James Salamon
  • 1,306
  • 1
  • 21
  • 18
33

I have faced this same issue. I solved it by doing following 2 things:

In root module's route configuration, use loadChildren with a relative path to the lazy loaded angular module. The string is delimited with a # where the right side of split is the lazy loaded module's class name.

I have added ./ as prefix to the loadChildren string.

{ path:'user', loadChildren:'./app/user/user.module#UserModule'}

I am using webpack 2 and it needs a loader for Angular 2 that enables string-based module loading with the Angular Router. Add this to the project

yarn add angular-router-loader -D

then add the angular-router-loader to typescript loaders

loaders: [
  {
    test: /\.ts$/,
    loaders: [
    'awesome-typescript-loader',
    'angular-router-loader'
    ]
  }
]

and its working for me.

Jasnan
  • 3,298
  • 1
  • 16
  • 22
  • 1
    I had to omit the `app` part also: `{ path:'user', loadChildren:'./user/user.module#UserModule'}` – Felix Oct 25 '17 at 07:56
  • @Jasnan where to add this `loaders`, I don't know which file it is – Nikhil Radadiya Nov 03 '17 at 15:06
  • @NikhilRadadiya `loaders` are in `webpack.config.js` file. But if you're using `angular-cli` you won't have this file unless you will use `ng eject`, but it's not recommended in projects build with `angular-cli` – arthurr Nov 20 '17 at 15:21
33

For newer Angular versions (10+?) lazy loading is done using the following syntax:

{ path: "foos", loadChildren: () => import ("./foos/foo.module").then(m => m.FooModule) },

I met a similar issue when working with Angular 4.4.5 and webpack and managed to fix it without using strings, but module type reference (much easier to write and less error prone):

const routes: Routes = [
  { path: '', loadChildren: () => TestModule }
];

I could not find the minimum version for Angular (loader) the supports this syntax.


A way that might work with AOT is to replace lambda syntax with a regular one:

export function getTestModule() { return TestModule; }

const routes: Routes = [
  { path: '', loadChildren: getTestModule }
];

Also check this issue (thanks to rey_coder).

Alexei - check Codidact
  • 17,850
  • 12
  • 118
  • 126
  • I would prefere this solution but i does not work for me. `ERROR in Error: Error encountered resolving symbol values statically. Reference to a local (non-exported) symbol 'appRoutes'. Consider exporting the symbol (position 8:7 in the original .ts file), resolving symbol AppRoutingModule` – Pascal Oct 26 '17 at 13:16
  • @Pascal - how is your module exported? I simply export it without `default`: `export class TestModule { }` – Alexei - check Codidact Oct 26 '17 at 17:45
  • @Alexei How to use it, import TestModule in app.routes and then use it like ``loadChildren: () => TestModule`` ? I'm doing similarly with my app but getting above mentioned error ERROR in Error: Error encountered resolving symbol values statically. and if I do it with string I get ``cannot-find-module`` – Nikhil Radadiya Nov 06 '17 at 14:30
  • @Sam - unfortunately, you are right. I had to use `loadChildren` with the path. – Alexei - check Codidact Jan 12 '18 at 05:40
  • Thank you so much! this helped tremendously! You helped us out of a literal misery! – Kevin de Goede Jul 03 '18 at 09:10
  • This worked for me... angular cli version 6.0.8. I got to follow the issue [here](https://github.com/angular/angular-cli/issues/10673#issuecomment-391850980) on github – rey_coder Jul 10 '18 at 23:00
  • DANGER!!!! THIS DOES NOT FIX YOUR PROBLEM!! THIS BREAKS LAZY LOADING!! Since your loadChildren reference is a function, is it bundled WITH your main app chunk using this method. DO NOT DO THIS if you want to lazy load your module!! – dudewad Apr 17 '19 at 04:15
  • This was the only thing that worked for me. thanks. – Joel Jan 12 '20 at 02:29
19

For people who are using a recent Angular version (v9 in my case), you can setup your route with the following syntax declaration:

import { TestModule } from './modules/test.module';
const appRoutes: Routes = [
  { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
];

// NgModule
// declarations
// imports
// providers
// bootstrap

export class AppModule { }

Another way (without making the import at the top):

    const appRoutes: Routes = [
      { path: 'blogs', loadChildren: () => import('./modules/test.module').then(m => m.TestModule) },
    ];
Mugiwara
  • 701
  • 6
  • 14
  • the first way, is it really needed? seems to me that TestMudule is never used... the import that's working is the one in () => import – João Otero Apr 12 '20 at 00:29
  • This of all the answers have solved my problem, not the ng serve restart nor the relative paths. Upvoting so this would come top as accepted answer. – Bendram Apr 20 '20 at 02:49
  • In Angular 9 this solved my problem! I used the second version without the import at the top. Thanks so much for sharing! – Michael F. Jun 24 '20 at 13:02
12

Finally I found out that I need to import lazy loaded module in routing config this way:

const routes: Routes = [
   { path: '', loadChildren: 'app/test.module' }
];

without any / or ./in front of module path.

arthurr
  • 1,075
  • 1
  • 10
  • 19
4

In Angular 9 I did this and it worked for me: loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)

You can have a look on official documentation

Zohab Ali
  • 4,958
  • 3
  • 31
  • 43
3

I change this

{
            path: 'test',
            loadChildren: 'app/tests/test.module#TestModule'

}

for this

   {
        path: 'test', loadChildren: () => new Promise(resolve => {
            (require as any).ensure([], require => {
                resolve(require('app/tests/test.module').TestModule);
            })
        })
    },

And solved my problem.

Ruby Junior Dev
  • 118
  • 1
  • 4
3

It was worked for me by using.

../app/

I solved this issue by using the suggestion popup in VS code. You can also follow that. No need to go anywhere. (I Think, the path may vary in every project.)

Roney Francis
  • 366
  • 2
  • 15
2

I've been troubleshooting this for a a couple of hours on a project I've just taken over from. None of the above solutions were working, but then I realised that all the lazy-loaded modules had the .ts extension.

If anyone else is having issues, check if you need to change loadChildren: 'app/example.module.ts' to loadChildren: 'app/example.module'.

Runny Yolk
  • 865
  • 3
  • 16
  • 39
1

In a use-case scenario to segregate a distinct feature (e.g. test.module.ts) from its root application (i.e. app.module.ts) through a lazily-loaded module, we could create the test module and it's components in a sub-folder (e.g. src/app/test/). The test-routing.module could be configured this way:

//test-routing.module.ts
//routes to test.component.ts as an example

import { Routes, RouterModule } from '@angular/router';
import { TestComponent } from './test.component';

const feature_test_routes: Routes = [

    { 
        path: '',
        component: TestComponent
    }

];

export const TestRoutingModule = RouterModule.forChild(feature_test_routes);

The "parent" module (app-routing.module.ts), would have a route that looks like this:

//app-routing.module.ts
//routes to http://localhost:4200/test

import { Routes, RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
const root_routes: Routes = [

    { 
        path: '',
        component: AppComponent, 
        children: [
            {
                path: 'test',
                loadChildren: './test/test.module#TestModule'
            }
        ]
    }

];

export const AppRoutingModule = RouterModule.forChild(root_routes);

This allows the root application and entry component, imperatively loaded, to subsequently lazy-load features from test.module.ts as a child when needed.

Pageii Studio
  • 2,016
  • 1
  • 12
  • 17
1

make sure to include import { Routes, RouterModule } from '@angular/router'; in the module to load lazely

da45
  • 271
  • 1
  • 3
  • 11
1

I had a similar issue. I just restarted the server and it worked. :)

Ankita P.
  • 478
  • 8
  • 21
1

I have solved my own issue. Don't put the .ts in the path name. Rather than using 'path/to/my/module.ts#MyModuleClass', use 'path/to/my/module#MyModuleClass'

alaboudi
  • 2,442
  • 2
  • 22
  • 39
1

In my case the path shared the same route as one I declared elsewhere, assuming they would be relative paths. e.g like below in the

Not Working

Admin Module

    {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: './organisation/organisation.module#AdminOrganisationModule',
    },

User Module

    {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: './organisation/organisation.module#UserOrganisationModule',
    },

individually, when only one was declared, these were working fine, but not together as it complained about the ./organisation/organisation.module path , I changed both to the pattern below and it was ok.

Working

Admin Module

    {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: '../admin/organisation/organisation.module#AdminOrganisationModule',
    },

User Module

        {
    path: 'organisation',
    canActivate: [AuthGuard],
      loadChildren: '../user/organisation/organisation.module#UserOrganisationModule',
    },
Ray_Hack
  • 903
  • 1
  • 9
  • 23
0

You need to change

export default class TestModule { }

to

export class TestModule { }

That should fix your problems

Wambua Makenzi
  • 517
  • 3
  • 6