在 ES5 中创建自定义元素 v1,而不是 ES6

Create custom elements v1 in ES5, not ES6

目前,如果您完全遵循 v1 of the custom elements spec 的规范,则无法在不支持 classes 的浏览器中使用自定义元素。

是否可以使用 class 语法创建 v1 自定义元素 而无需 ,以便它们在 Chrome、FireFox 和 IE11 中完全可用。此外,由于 IE11 没有对自定义元素的原生支持,我假设我们可能需要使用一些 pollyfills,那么我们需要哪些 polyfills 或库才能在 IE11 中完成这项工作?

我已经弄乱了 Polymer 2、Polymer 3 和 Stencil,但对于我们想要创建的某些东西来说,它们都有些繁重。

似乎在正确的轨道上,但我在 IE11 中遇到了一些问题,那么我如何在 IE11 中使用 Reflect.construct 来实现自定义元素的目的?

这是使用 v1 规范编写兼容 ES5 的自定义元素的完整示例(归功于 this comment on github

<html>

<head>
  <!--pollyfill Reflect for "older" browsers-->
  <script src="https://cdn.rawgit.com/paulmillr/es6-shim/master/es6-shim.min.js"></script>
  <!--pollyfill custom elements for "older" browsers-->
  <script src="https://cdn.rawgit.com/webcomponents/custom-elements/master/custom-elements.min.js"></script>
  <script type="text/javascript">
    function MyEl() {
      return Reflect.construct(HTMLElement, [], this.constructor);
    }

    MyEl.prototype = Object.create(HTMLElement.prototype);
    MyEl.prototype.constructor = MyEl;
    Object.setPrototypeOf(MyEl, HTMLElement);

    MyEl.prototype.connectedCallback = function() {
      this.innerHTML = 'Hello world';
    };
    customElements.define('my-el', MyEl);
  </script>
</head>

<body>
  <my-el></my-el>
</body>

</html>

此外,对于 typescript 爱好者,这里有一种使用 typescript 编写自定义元素的方法,它在编译为 ES5 时仍然有效。

<html>
<head>
    <!--pollyfill Reflect for "older" browsers-->
    <script src="https://cdn.rawgit.com/paulmillr/es6-shim/master/es6-shim.min.js"></script>
    <!--pollyfill custom elements for "older" browsers-->
    <script src="https://cdn.rawgit.com/webcomponents/custom-elements/master/custom-elements.min.js"></script>
    <script type="text/typescript">
        class MyEl extends HTMLElement{
          constructor(){
              return Reflect.construct(HTMLElement, [], this.constructor);
            }  
            
            connectedCallback () {
              this.innerHTML = 'Hello world';
          }
        }

        customElements.define('my-el', MyEl);
    </script>

</head>

<body>
    <my-el></my-el>
    <!-- include an in-browser typescript compiler just for this example -->
    <script src="https://rawgit.com/Microsoft/TypeScript/master/lib/typescriptServices.js"></script>
    <script src="https://rawgit.com/basarat/typescript-script/master/transpiler.js"></script>
</body>

</html>