If I could just write Svelte code all day I would be a happier person in general. It comes with an extremely useful feature, the ability to compile components as custom elements. Svelte was an early adopter of custom elements among frameworks, which makes it easy to use a Svelte component anywhere (mostly). In my opinion not much is better.
So what is a custom element version of a svelte component? It's a web component. And that means it can be used in a plain old html file or consumed by other frameworks such as Angular, Vue, or React. Sure there are other frameworks that do it too, Lit for instance, which was made for writing web components. But then you would lose the quality of life that comes from writing Svelte code.
Using this feature is fairly straightforward. The rest of the article assumes you have a fresh svelte project. Below I'll show you how to make a component bundled as a custom element and switch the project to library mode. This way the build actually creates an individual JavaScript file for the web component. This bundled file is how you can distribute your Svelte component.
Here's a regular svelte component, we'll convert this to a web component:
To turn this into a web component, we need to add something to the fist line of the file, add this:
And create the Svelte file at the path src/lib/my-web-component.svelte, the content in my file looks like this (I changed a few other things, variable names and text content):
Next, update svelte.config.js in your project, this tells the compiler to bundle a custom element:
And to make this useable anywhere else, we need to update vite to package the component into a single file. Update vite.config.ts:
And then when you go to compile your svelte library, the component is built into a standalone web component. The output is a JavaScript file that can be added via a script tag or consumed by another framework. In this case the bundler creates a file at the path dist/my-web-component.js and it can be copied around as a standalone JavaScript module.
Here's an example of how you might use this in an html website, assuming the JavaScript file is copied right next to the index.html file, your html file looks like this:
The component is now usable across frameworks! I created a repository with examples in plain html (web), react, angular and vue: github.com/benjaminknox/svelte-components-as-web-components-examples
I hope you enjoy coding in Svelte 👋