Thursday, September 15, 2022

Web Components Introduction: Stencil, Lit, lwc

An Introduction to Web Components @academind

Learn how to get started with web components to build re-usable components (for all frameworks!) with vanilla JavaScript.

by Maximilian Schwarzm├╝ller of academind

Web Components consists of three main technologies, which can be used together to create versatile custom elements with encapsulated functionality that can be reused wherever you like without fear of code collisions.
  • Custom elements: A set of JavaScript APIs that allow you to define custom elements and their behavior, which can then be used as desired in your user interface.

  • Shadow DOM: A set of JavaScript APIs for attaching an encapsulated "shadow" DOM tree to an element — which is rendered separately from the main document DOM — and controlling associated functionality. In this way, you can keep an element's features private, so they can be scripted and styled without the fear of collision with other parts of the document.

  • HTML templates: The <template> and <slot> elements enable you to write markup templates that are not displayed in the rendered page. These can then be reused multiple times as the basis of a custom element's structure.

Lit is a simple library for building fast, lightweight web components.

Stencil employs JSX, while lit-element has to use lit-html as it's templating language to render to the shadow DOM. The syntax is slightly different, but similar enough that it's not a huge barrier.

if you want something as close to the standard as possible, with no extra baggage — go for lit-element. If you don't want to setup testing, go through as much boilerplate, or develop a build process — use Stencil.