Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module in Angular routing

My folder structure is:

+-- app.module.ts
+-- app.routing.ts
+-- app.component.ts
+-- account/
|   +-- account.module.ts
|   +-- account.routing.ts
|   +-- account.component.ts

In my app.routing.ts I have,

  { path: 'account', loadChildren: './account/account.module#AccountModule' },

And, in account.routing.ts, I have,

  { path: 'login', component: LoginFormComponent}

but when I enter page/account/login I get the following error:

NodeInvocationException: Uncaught (in promise): Error: Cannot find module './account/account.module'. Error: Cannot find module './account/account.module'.

I've tried changing ./account/account.module#AccountModule to app/account/account.module#AccountModule, same error.

Any thoughts? Thanks in advance.

like image 886
Zair Henrique Avatar asked Dec 04 '22 21:12

Zair Henrique


2 Answers

you can try changing

  { path: 'account', loadChildren: './account/account.module#AccountModule' }

to

import {AccountModule} from './path';

{ path: 'account', loadChildren: ()=> AccountModule' }

note - do not forget to import module as above

like image 80
S.Pradeep Avatar answered Dec 29 '22 07:12

S.Pradeep


The string version of loadChildren has been deprecated in angular 8

See: https://github.com/angular/angular/blob/master/CHANGELOG.md#800-2019-05-28 See: https://angular.io/api/router/LoadChildren

New syntax in angular 8/9

The new syntax takes a dynamic import expression. This is a function that returns an import. It is critical that you import your module there. Otherwise you are not lazy loading the module, but eagerly loading it.

{ 
path: 'account', 
loadChildren: ()=> import('./account/account.module').next(mod => mod.AccountModule) 
}

The docs: https://angular.io/api/router/LoadChildrenCallback

New syntax in angular 10

In angular 10 the syntax slightly changed again. Now it provides the import as a result of a JavaScript Promise ( import returns a Promise: ):

{ 
path: 'account', 
loadChildren: ()=> import('./account/account.module').then(mod => mod.AccountModule) 
}

Warning: Assigning a module after importing will not lazy load your module!

S.Pradeep's solution will still eagerly load the module! You can check for yourself by implementing both approaches while checking the new (lazy loaded) network request navigating to a lazy loaded path.

like image 24
Rob Monhemius Avatar answered Dec 29 '22 07:12

Rob Monhemius