使用babel透明化基于类的Web组件 [英] Transpiling class based web components with babel

查看:89
本文介绍了使用babel透明化基于类的Web组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a simple web component following the latest web components v1 class syntax, it works great in Chrome and Firefox/Edge (with a polyfill) but I'd like it to run in IE11 so I need to transpile the class. However running it through babel produces code that no longer works in any browser.

有没有办法用类语法生成向后兼容的Web组件,或者是否有一种首选方式编写Web组件以获得最大兼容性?

Is there any way to generate backwardly compatible web components with the class syntax or is there a preferred way to write web components for maximum compatibility?

示例代码 -

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

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

使用转换代码时的错误消息是 -

Error message when using transpiled code is -


未捕获TypeError:无法构造'HTMLElement':请使用'new'运算符,这个DOM对象构造函数不能作为函数调用。

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


推荐答案

要使用Babel编译自定义元素类,您可以使用此插件来自Github。

To compile Custom Element classes with Babel, you can use this plugin from Github.

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

It will use Reflect.construct() instead of new, which is not permitted with HTMLElement objects.

这篇关于使用babel透明化基于类的Web组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆