【问题标题】:Dynamic Component Loading with Webpack Code Splitting使用 Webpack 代码拆分的动态组件加载
【发布时间】:2017-04-06 07:59:33
【问题描述】:

为了加载动态组件,我使用了 materail 选项卡,如下所示:

<md-tab-group [selectedIndex]="selectedTabIndex" *ngIf="tabs && tabs.length > 0">
    <md-tab *ngFor="let tab of tabs">
        <template md-tab-label>
            {{tab.title}}
            <span class="k-icon k-i-close mat-tab-close" (click)="close(tab)"></span>
        </template>
        <dcl-wrapper [type]="tab.component"></dcl-wrapper>
    </md-tab>
</md-tab-group>

我想将来自不同模块的组件加载到此选项卡中。加载过程是使用 dcl-wrapper 完成的,如以下链接所示:

https://stackoverflow.com/a/37154680/5285133

我使用 webpack 代码拆分策略将单独的模块组件提供给 dcl-wrapper。

require.ensure(["../../dmy/dmy.module"], (reqire : any) => {
    let cmp = require("../../dmy/page/page2")["Page2"];
    this.tabs.push({ title: "--", component: cmp });
    this.selectedTabIndex = this.tabs.length - 1;
    this._cdr.detectChanges();
}, "dmy");

但我收到“No component factory found for Page2. You add it to @NgModule.entryComponents?”错误。

我也尝试使用 SystemJsNgModuleLoader 以这种方式加载单独的模块组件:

this._loader.load('../../dmy/dmy.module#DMYModule').then((factory: NgModuleFactory<any>) => {
    console.log(factory);
});

它给出了这个错误:

错误:找不到模块“../../dmy/dmy.module”。?在 webpackEmptyContext

由于我使用选项卡组件而不是路由,因此延迟加载不是我想要的解决方案。所以,我寻找一种方法来获取单独模块组件的实例。

您对我如何动态加载单独的模块及其组件有什么建议吗?

【问题讨论】:

  • No component factory found for Page2. 您是否将此组件添加到entryComponents 数组中?如果是这样,那么您在哪个模块(或组件)中添加了它?
  • Cannot find module '../../dmy/dmy.module'. 也许您需要尝试其他路径,即app/dmy/dmy.module#DMYModule
  • 你的DMYModule看起来怎么样?
  • 1.将 Page2 或任何其他组件添加到 entryComponents 不是 webpack 建议的方式。 2.我尝试了很多路径变体,但这与路径无关,问题是我认为 SystemJsNgModuleLoader 不能与 webpack 一起使用。 3. DMYModule 是一个简单的模块,里面有一些测试页面。
  • ComponentFactoryResolver 需要编译的组件,只需将此组件添加到entryComponents 数组即可。这样 angulat 将为此组件编译工厂并在 ComponentFactoryResolver 中保存到该工厂的链接

标签: angular webpack


【解决方案1】:
System.import("../../dmy/dmy.module.js")
            .then((module: any) => {
                return module["DMYModule"];
            }).then((type: any) => {
                return this._compiler.compileModuleAndAllComponentsAsync(type);
            }).then((moduleWithFactories: ModuleWithComponentFactories<any>) => {
                const factory = moduleWithFactories.componentFactories.find((x: any) => x.componentType.name === "Page1"); 
                this.tabs.push({ title: "--", component: factory["componentType"], factory: factory });
                this.selectedTabIndex = this.tabs.length - 1;
                this._cdr.detectChanges();
            });

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 2018-09-13
    • 2023-03-12
    • 2016-02-11
    • 2017-12-14
    • 1970-01-01
    相关资源
    最近更新 更多