我有一个遵循最新 web components v1 class syntax 的简单网络组件,它在 Chrome 和 Firefox/Edge(带有 polyfill)中运行良好,但我希望它在 IE11 中运行,所以我需要转换该类。然而,通过 babel 运行它会产生不再适用于任何浏览器的代码。
是否有任何方法可以使用类语法生成向后兼容的 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.
最佳答案
要用 Babel 编译自定义元素类,你可以使用这个 plugin来自 Github。
它将使用 Reflect.construct()
而不是 new
,这是 HTMLElement
对象所不允许的。
关于javascript - 使用 babel 转译基于类的 Web 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41414034/