Exporting Web Components (customElement) #202
-
QuestionI love this library and I love Svelte. I want to embed the functionality here into a HTMX / HTML project, so was wondering if it's possible to export Web Components from In theory this should be possible, as Svelte support Web Component output. I was wondering if anyone has ever tried this, or could suggest a good approach for doing so? Idea
Note In theory, exporting web components would make this library available to use in any other library, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
As described in this post, attempting to re-export as a web component in the standard Svelte way may cause issues: https://medium.com/@yesmeno/svelte-components-as-web-components-b400d1253504 I'm thinking of creating a wrapper for each Svelte component as a customElement, with a separate Vite config for the compile, like so: import MapLibre from './lib/components/MapLibre.svelte'
import type { SvelteComponent } from 'svelte'
customElements.define(
'maplibre',
class extends HTMLElement {
_element: SvelteComponent;
constructor() {
super()
// Create the shadow root.
const shadowRoot = this.attachShadow({ mode: 'open' })
// Instantiate the Svelte Component
this._element = new MapLibre({
// 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(','),
// this could be made generic / less prone to breakage on update simply doing something like this.attributes.forEach(x => JSON.stringify(x))
},
})
}
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();
}
}
) Usage: <maplibre prop1="" prop2=""></maplibre> The web components could then be made available as a separate package, something like Or even better this could go under an org 🙏 |
Beta Was this translation helpful? Give feedback.
Yeah, a separate package feels like the best way to go, even if the code for it lives in this same repository. I like the idea of publishing as web components but have neither the time nor the existing knowledge to take it on at the moment, so thanks for your efforts here :)