在 angular 项目中使用多个 angular 元素作为 web 组件

Col*_*ens 4 web-component angular angular-elements

鉴于3个@angular项目全部使用v6.1.9: ,hostalphabeta

alphabeta使用 @angular/elements 创建和定义一个 web 组件,如下所示:

constructor(private injector: Injector) {}

ngDoBootstrap() {
  const config: NgElementConfig = { injector: this.injector };
  const component= createCustomElement(component, config);
  customElements.define("alpha-component", component); // beta-component respectively
}
Run Code Online (Sandbox Code Playgroud)

alphabeta使用ng build --prod --output-hashing none构建,然后运行后构建脚本以按以下顺序连接生成的文件:scripts.js, styles.js, runtime.js, main.js

polyfills.js 被跳过,因为main.ts在加载库时会检查所使用的 polyfills 是否已经定义(例如避免尝试重新定义 zone.js)。

得到的束是alpha-component.bundle.jsbeta-component.bundle.js

host引用了上述束<head>index.html<script defer>标签。

如果以alphathen的顺序引用包beta,我会看到alpha尝试引导两次;以相反的顺序,我会看到beta尝试引导两次。

由于第一个引用的 bundle 尝试引导两次,它尝试为 bundle 定义 web 组件两次,导致错误,并且永远不会注册第二个引用的 bundle 的 web 组件。

目标是能够使用@angular 创建许多 Web 组件,然后在其他 @angular 或insert framework here技术中使用它们。

Man*_*yer 5

不幸的是,bundle 的连接在这里不起作用,b/c webpack 使用的是全局变量。由 alpha 包创建的变量将被 beta 包的变量覆盖。

你可以在包中重命名这个变量,或者你可以使用 [1] 并且它是 --single-bundle 开关。

首先,忘记自述文件关于外部的内容。这是进一步的优化技术,其中主机、alpha 和 beta 可以共享相同的库。这可以防止您多次加载 Angular。

也许,我关于 Angular Elements 的博客系列也对您很有趣 [2]。

最好的祝福,曼弗雷德

[1] https://github.com/manfredsteyer/ngx-build-plus

[2] https://www.softwarearchitekt.at/post/2018/07/13/angular-elements-part-ia-dynamic-dashboard-in-four-steps-with-web-components.aspx

  • 发布后,我意识到 ngx-build-plus 库中存在 --single-bundle 开关。 (2认同)