Transpiling class based web components with babel
Asked Answered
H

2

14

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.

Hayley answered 1/1, 2017 at 7:32 Comment(5)
Could this be a duplicate of #35003913 which is a duplicate of #33833146 - if it is, then next time try searching for transpile OR babel extendsIntentional
That sounds like the underlying problem, I'm interested in how people work around this in relation to web components - or can the two not work together?Hayley
Workaround? https://mcmap.net/q/697786/-extending-built-in-natives-in-es6-with-babelIntentional
Thanks but after running with this transpiled code gives "TypeError: Illegal constructor"Hayley
I have never transpiled, I just tried to find you examples. I also did not hammer close as duplicate for the same reasonIntentional
A
6

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.

Alec answered 1/1, 2017 at 12:28 Comment(0)
T
5

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.

Thibaut answered 1/1, 2017 at 8:28 Comment(2)
Thanks, seems this is actually a duplicate of #39478178Hayley
works perfectly - after having had many trouble with other solutions. btw they say "We are also working on some future refinements to this approach that will improve the implementation and automatically detect if it's needed.". interestingly firefox does not need the shim.Engelhart

© 2022 - 2024 — McMap. All rights reserved.