herodevs/herodevs-packages

Option "lazyModules" is deprecated

AE1NS opened this issue · 1 comments

AE1NS commented

I get the following console output when building my app:

[ng] Option "lazyModules" is deprecated: 'SystemJsNgModuleLoader' is deprecated, and this is part of its usage. Use 'import()' syntax instead.

Do you know if there is another way to declare this modules dynamically in the future? As far as I know, with the import() method you have to reference the module by a string file path (so far so good), but also by a lambda expression where you cant use strings. So this would be no solution for me. https://angular.io/guide/lazy-loading-ngmodules

AE1NS commented

There is a modern angular way to achieve what the hero-loader is doing. You do not need to add the modules to the lazyModules Array in the angular.json anymore (chunks are created automatically). The entry component must still be in the bootstrap array with this solution:

private _componentRef;

constructor(
        private _injector: Injector,
        private _viewRef: ViewContainerRef,
        private _renderer: Renderer2,
        private _compiler: Compiler,
        private _applicationRef: ApplicationRef
) {}

loadModule() {
    import('path/to/module/my.module')
        .then((module) => module[Object.keys(module)[0]])
        .then((module) => this._compiler.compileModuleAsync(module))
        .then((factory) => {
            const moduleRef = factory.create(this._injector);
            const component = (moduleRef as any)._bootstrapComponents[0];
            this._componentRef = moduleRef.componentFactoryResolver.resolveComponentFactory(component).create(this._injector, [], null, moduleRef);    
            // Set component input variables
            this._componentRef.instance.test = 'test';
            this._applicationRef.attachView(this._componentRef.hostView);
            this._renderer.appendChild(this._viewRef.element.nativeElement, this._componentRef.location.nativeElement);
        });
}

destroyComponent() {
    this._applicationRef.detachView(this._componentRef.hostView);
}
  • your tsconfig.json should contain something like
    "include": ["src/**/*.ts"],
    "exclude": ["src/test.ts", "src/**/*.spec.ts", "src/environments/environment.*.ts"]

to get your chunks created automatically