Search code examples
javascriptangulartypescriptweb-componentangular-elements

Polyfill Support for Angular 9 Custom Elements?


What does Angular recommend for Polyfilling support for custom elements built with Angular?

This demo works with only this polyfill added to polyfills.ts:

import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'

This article says we should include the following in polyfills.ts:

import "@webcomponents/custom-elements/src/native-shim";
import "@webcomponents/custom-elements/custom-elements.min";

And this article says we should add the following to index.html:

<script src="webcomponents/webcomponents-loader.js"></script>
<script>
  if (!window.customElements){document.write('<!--');}
</script>
<script src="webcomponents/custom-elements-es5-adapter.js"></script>
<!-- ! DO NOT REMOVE THIS COMMENT, WE NEED ITS CLOSING MARKER -->

So there are differences. Which approach is the correct one for Angular 9 projects when deploying custom elements built with Angular?


Solution

  • it all depends on which browsers you want to support and bundle syntax that your application is generating.

    @webcomponents/custom-elements/src/native-shim and @webcomponents/webcomponentsjs/custom-elements-es5-adapter.js serve the same purpose, these are used if the browser does not support ES2015 modules or because the application is explicitly configured to generate ES5 only bundles.

    @webcomponents/custom-elements and @webcomponents/custom-elements/src/native-shim also serve the same purpose which is to provide support for custom elements for browsers that do not natively support Custom Elements.

    More information about those polyfills and why and when they are needed;

    I wouldn't recommend on using the below pattern.

    <script src="webcomponents/webcomponents-loader.js"></script>
    <script>
     if (!window.customElements){document.write('<!--');}
    </script>
    <script src="webcomponents/custom-elements-es5-adapter.js"></script>
    <!-- ! DO NOT REMOVE THIS COMMENT, WE NEED ITS CLOSING MARKER -->
    

    A better alternative would be;

    <script src="webcomponents/webcomponents-loader.js"></script>
    <script nomodule src="webcomponents/custom-elements-es5-adapter.js"></script>