angularweb-componentangular-elements

Using multiple angular elements as web components within an angular project


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.


Solution

  • 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