首页 > 解决方案 > 是否可以将 Web 组件动态导入到在 Angular 8 上运行的 Ionic 5 应用程序中?

问题描述

我有一个 Ionic 5 混合应用程序(使用 Angular 8 完成繁重的工作),我想动态导入我之前使用 @angular/elements 生成的 Web 组件。

这个想法是使用像函数一样工作的 import 的变体,如mdn中所述,如下所示:

import('/modules/my-module.js').then(module => {...})

我已经创建了 Web 组件,如果我静态导入它们,它们可以正常工作,如下所示:

import '../webcomponents/item.js';

然而,动态地,所有的赌注都被取消了。一开始我以为 webpack 正在破坏路径,但没有那么复杂。看看有什么作用:

import('../webcomponents/item.js').then(mm => {...})

奇迹般有效。

const path = '../webcomponents/item.js';
import(path).then(mm => {...})

Uncaught (in promise): Error: Cannot find module '../webcomponents/item.js'得到以下反应:

Warnings while compiling
...
Critical dependency: the request of a dependency is an expression

有什么想法可以在这里工作吗?区别只是在 import() 中直接将路径用作字符串,还是先将其放入变量中。那是什么巫术?webpack 还在干扰吗?我已将整个应用程序简化为这段代码,因此这里没有太多其他可能发生的问题:

import { Component } from '@angular/core';

import('../webcomponents/item.js').then(mm => {}); // works

const path = '../webcomponents/item.js';
import(path).then(mm => {}); // doesn't

@Component({
    selector: 'app-root',
    template: ``,
    styles: [],
})
export class AppComponent {}

标签: angularionic-frameworkdynamicimportweb-component

解决方案


推荐阅读