Transpiling class based web components with babel

2019-02-13 00:41发布

问题:

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.