Search code examples
javascriptbabeljsweb-componentcustom-element

Transpiling class based web components with 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.

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.


Solution

  • 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.