Last active
June 23, 2023 22:46
-
-
Save enyo/cf5e31d822338f979cb7a85b86a1a8fb to your computer and use it in GitHub Desktop.
Svelte Web Components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import HeaderMenu from './lib/components/HeaderMenu.svelte' | |
import type { SvelteComponent } from 'svelte' | |
customElements.define( | |
// I recommend prefixing your custom elements, but for this example | |
// I'm keeping it simple. | |
'header-menu', | |
class extends HTMLElement { | |
_element: SvelteComponent; | |
constructor() { | |
super() | |
// Create the shadow root. | |
const shadowRoot = this.attachShadow({ mode: 'open' }) | |
// Instantiate the Svelte Component | |
this._element = new HeaderMenu({ | |
// Tell it that it lives in the shadow root | |
target: shadowRoot, | |
// Pass any props | |
props: { | |
// This is the place where you do any conversion between | |
// the native string attributes and the types you expect | |
// in your svelte components | |
items: this.getAttribute('items').split(','), | |
}, | |
}) | |
} | |
disconnectedCallback(): void { | |
// Destroy the Svelte component when this web component gets | |
// disconnected. If this web component is expected to be moved | |
// in the DOM, then you need to use `connectedCallback()` and | |
// set it up again if necessary. | |
this._element?.$destroy(); | |
} | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
when I try to use this, I get this browser error:
alert-this.customElement.js:1 Uncaught TypeError: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function.
at new e (alert-this.customElement.js:1:3647)
I'm using sveltekit 4
this is my rollup.config.js file:
--- edit:
Found a solution
(https://github.com/ezolenko/rollup-plugin-typescript2)