We can lazy load a local module like this module
{
path: 'somePpath',
loadChildren: 'app/path/some.module#SomeModule'
},
How do we lazy load a module that comes from an external library resides in node_modules?
To load an external module in the router module you might need to use a Wrapper module. Create a wrapper module in the same local project in which you are having your routing module. Import your external module in this wrapper module with traditional import syntax.
import { SomeModule } from '@externalLib';
Include this module in the imports of NgModule's import array.
@NgModule({
imports: [SomeModule]
})
export class SomeWrapperModule {
}
Then use this wrapper module in the router module as we usually use a module.
// for Angular 7 and below
{
path: 'some-path',
loadChildren: '../somewrapper.module#SomeWrapperModule'
}
// for Angular 8+
{
path: 'some-path',
loadChildren: () => import('../somewrapper.module').then(mod => mod.SomeWrapperModule)
}
I'm not sure since which version, but at least since version 13 you can lazy load a node module anywhere directly in a method.
I use it, for example, when exporting data to excel, which is rarely run. Example:
public export(): void {
import('xlsx').then(xlsx => {
xlsx.writeFile(...);
});
}
SomeModule from 'some-lib' and use some components from that module like: <some-comp></some-comp>, you cannot just run import('some-lib').then() to use the components you want.I have found other ways instead of creating a wrapper module which by the way is not very pleasant, follow below some more fancy approaches:
loadChildren: '../../node_modules/lazy/lazy.module#LazyModule'. It works for meNgModulethat we know works. So where the OP is asking to "lazy load a library" ( i.e lodash ), then that is just not what the feature here is about.