Web Components with Svelte-3

Tal Singh
2 min readMay 22, 2021

Svelte has been the talk of the town in recent months, and its popularity has risen sharply with version 3. The project has now reached 47k stars on GitHub!

Svelte converts your app into ideal JavaScript at build time, rather than interpreting your application code at run time.

While Svelte is gaining popularity as a Single Page Application framework, many developers are still wondering if svelte is a safe choice for making web components?

The bundle size gives svelte an edge over its competitors. This makes it a de-facto choice for the web-development.

State of JS survey 2020

State of the JS survey predicts that the svelte is already popular among the developers for SPA. However, custom-elements with svelte stills remain unexplored territory. Most developers are unaware of the fact that they can also create web-components using svelte and use it as a plug and play widget.

To make your life easier, I have created a ready to use svelte boilerplate for webcomponents development with good documentation, installation steps and build (Don't forget to star the repo 🙏 )

TLDR — https://github.com/tal1992/svelte-webcomponents

The world’s most easiest, ready to use template for web-components.

A ready to use project template to build custom elements (web components) with Svelte 3 with support and examples for -

✓ Custom-elements

✓ jest

✓ sass

✓ nested web-components with props

✓eslinting

✓ stylelinting

✓ Github actions

✓ custom events from shadow-DOM to real-DOM

Installation

git clone https://github.com/tal1992/svelte-webcomponents.gitcd svelte-webcomponents 

once you are inside the folder, follow the below steps -

npm install

Run build in developer mode -

npm run dev

Run build in prod mode -

npm run build

Using web-components in HTML

<component-name propOne="Lorem" propTwo="Ipsum"></component-name>

Using web-components as a widget

function addScript(src) {
var s = document.createElement("script");
s.setAttribute("src", src);
document.querySelector("body").appendChild(s);
}
//replace the url with your hosted path of bundle.js
addScript("https://loremipsumdolarsir/build/bundle.js", "", "");

Now that your bundle.js file is included in the html , we can use the web components.

let foo = document.createElement('component-foo');
let header = document.getElementByTagName('header');
foo.setAttribute('propOne', "lorem");
foo.setAttribute('propTwo', "Ipsum");
// please replace header with desired element to place comp.
header.parentNode.replaceChild(foo, header);

Full documentation — https://github.com/tal1992/svelte-webcomponents

--

--