'Angular - Typescript dynamic import module using variable
I'm building an Angular app that lazy loads modules without routing, simulating plugins.
I have this function in a Service that loads a module (hardcoded right now for simplicity), then renders the components returned in mainBarComponents()
(a method in IPluginModule interface) in the renderContainer
provided.
loadViewFromPlugin(pluginPath: string, renderContainer: ViewContainerRef): any {
import(pluginPath).then(({MiPrimerPluginModule}) => {
// Compile the module
this.compiler.compileModuleAsync(MiPrimerPluginModule).then((moduleFactory: { create: (arg0: Injector) => any; }) => {
const moduleRef = moduleFactory.create(this.injector);
const moduleInstance: IPluginModule = moduleRef.instance;
const componentFactory = moduleInstance.mainBarComponents()[0];
const {instance} = renderContainer.createComponent(componentFactory);
// set component Input() property
// instance.title = 'foo';
// you have to manually call ngOnChanges for dynamically created components
// @ts-ignore
// instance.ngOnChanges();
});
});
}
The code works if I set pluginPath
as a literal string
import('./../../plugins/mi-primer-plugin/mi-primer-plugin.module').then(({MiPrimerPluginModule}) => {
But if I pass the parameter "pluginPath", then it throws at start:
./src/app/base/service/plugin-loader.service.ts:8:8-26 - Warning: Critical dependency: the request of a dependency is an expression
And when I want to initialize the module:
ERROR Error: Uncaught (in promise): Error: Cannot find module './../../plugins/mi-primer-plugin/mi-primer-plugin.module'
Error: Cannot find module './../../plugins/mi-primer-plugin/mi-primer-plugin.module'
How can I fix this issue, so the pluginPath can be dynamic?
And how I could generify
import(pluginPath).then(({MiPrimerPluginModule}) => {
^- this
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|