Using multiple angular elements as web components within an angular project

馋奶兔 提交于 2020-12-06 04:45:10

问题


Given three @angular projects all using v6.1.9: host, alpha, and beta

alpha and beta create and define a web component each using @angular/elements as such:

constructor(private injector: Injector) {}

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

alpha and beta are built using ng build --prod --output-hashing none and then a post build script is ran to concatenate the resulting files in the order of: scripts.js, styles.js, runtime.js, main.js.

polyfills.js is skipped because main.ts will check if the polyfills used are already defined when the library is loaded (to avoid trying to redefine zones.js for example).

The resultant bundles are alpha-component.bundle.js and beta-component.bundle.js.

host references the above bundles in the <head> of index.html with <script defer> tags.

If the bundles are referenced in the order of alpha then beta, I will see alpha trying to bootstrap twice; In the reverse order, I will see beta trying to bootstrap twice.

Since the first referenced bundle attempts to bootstrap twice, it attempts to define the web component for the bundle twice, causing an error, and never registering the second referenced bundle's web component.

The goal is to be able to create many web components using @angular and then consuming them within other @angular or insert framework here technologies.


回答1:


unfortunatelly, concatination of bundles does not work here, b/c webpack is using a global variable. The variable created by the alpha-bundle would be overwritten by the variable of the beta-bundle.

You could rename this variable in the bundles or you could go with [1] and it's --single-bundle switch.

To get started, forget about what the readme says about externals. This is an further optimization technqiue, where the host, alpha and beta could share the same libs. This prevents you from loading Angular several times.

Perhaps, also my blog series about Angular Elements is interesting for you [2].

Best wishes, Manfred

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

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



来源:https://stackoverflow.com/questions/52947217/using-multiple-angular-elements-as-web-components-within-an-angular-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!