I've created a sample Angular 6 Library with the angular cli
- ng new test-lib
- ng g library my-lib
This gives me the basic structure with the angular library "my-lib" and the sample app "test-lib" which I think can be used for testing purpose.
Inside the library, I want to use dynamic imports. I have a class which should be imported lazily:
export class Lazy {
print(): void {
console.log('I am lazy');
}
}
And I have my consumer component:
export class MyLibComponent implements OnInit {
async ngOnInit() {
const lazyImport = await import(/* webpackChunkName: 'lazy' */ './lazy');
new lazyImport.Lazy().print();
}
}
That's more or less about it. I use "ng build my-lib" to compile the library to the dist folder. In the tsconfig, I changed the "module" to esnext, to support dynamic imports.
Now I want to use the library inside of the sample app, which was generated by the cli. So inside of the app.module.ts, I import the module of the library and in the template of the app.component.ts, I add the corrensponding selector.
When I now build the sample app with "ng build" or start with "ng serve" I can see that there is no "lazy chunk" generated. It's just the normal main, polyfills, runtime, styles and vendor. What am I missing? Is it not possible to use dynamic load inside of a library?
When I change the import path inside of the app.module.ts from the compiled dist folder
import { MyLibModule } from 'my-lib';
to the librarys source code
import { MyLibModule } from '../../projects/my-lib/src/public_api';
the lazy chunk get's created and everything works as expected. But that's of course not what I want. I wand to use the compiled library inside of a totally different project where I can not import from the typescript sources.
Edit: Summary of my problem
Can a library itself perform dynamic loading or does this feature only work for the main-app to lazy load other parts of the app or additional libraries?!
Edit: Reason for the question
My library consists of hundreds of generated typescript classes. Per use case, only a few are needed. These should be loaded on demand.
Thanks for your help!
Stephan