简体   繁体   中英

Cannot get web component to work in codesandbox.io

I'm trying to get a customized built-in web component to work in codesandbox.io. This is the code:

 class MyDiv extends HTMLDivElement { constructor() { super(); } connectedCallback() { this.innerHTML = "works!"; } } customElements.define("my-div", MyDiv, {extends: 'div'}); 
 <div is="my-div"></div> 

The error I'm getting:

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

Tested in Chrome 67, Arch Linux. Here's the link: https://codesandbox.io/s/yqln560jzj

It does work here in a snippet, and it also works on codepen: https://codepen.io/connexo/pen/ZjEbqo

What am I missing here?

If it doesn't works it's because Codesandbox is using a kind a Javascript preprocessor (Typescript?) on external JS files, that will execute the code before (to detect syntaxt errors or so on).

The customElements.define() method is called twice, and fails the second time it is called because you can define a custom element only one time.

You can see it by calling customElements.get() inside your script, and see it's already defined.

console.log( customElements.get( 'my-div' ) )

If you put the Javascript inline (in the HTML file index.html ) in a element it will work fine.

Note that the second error you get it's because you are using the Babel preprocessor in the Codeopen snippet. You must disable Babel and it will work.

What am I missing here?

Nothing. It's codesandbox.io that is missing Custom Elements support.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM