Transpiling class based web components with babel

非 Y 不嫁゛ 提交于 2019-11-29 18:20:32

问题


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.

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?

Example code -

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

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

Error message when using transpiled code is -

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


回答1:


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

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




回答2:


One solution is to use the native-shim available with this polyfill https://github.com/webcomponents/custom-elements

It's not perfect though, would like to find a cleaner solution.



来源:https://stackoverflow.com/questions/41414034/transpiling-class-based-web-components-with-babel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!