使用 babel 转译基于 class 的 Web 组件

Transpiling class based web components with babel

我有一个遵循最新 web components v1 class syntax 的简单 Web 组件,它在 Chrome 和 Firefox/Edge 中运行良好(使用 polyfill),但我希望它 运行 在 IE11 中,所以我需要转译 class。但是 运行通过 babel 生成的代码不再适用于任何浏览器。

是否有任何方法可以使用 class 语法生成向后兼容的 Web 组件,或者是否有编写 Web 组件以获得最大兼容性的首选方法?

示例代码-

class TestElement extends HTMLElement {
  connectedCallback(){
    this.innerHTML = "<div>Testing</div>"
  }
}

customElements.define('test-element', TestElement)

使用转译代码时的错误信息是-

Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

一个解决方案是使用这个 polyfill 提供的 native-shim https://github.com/webcomponents/custom-elements

虽然还不完美,希望找到更清洁的解决方案。

要使用 Babel 编译自定义元素 类,您可以使用 Github 中的 plugin

它将使用 Reflect.construct() 而不是 newHTMLElement 对象不允许这样做。