Angular2 lazy loading module error 'cannot find module'
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) },
];
restarting ng serve
worked for me
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.
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
).