Web Components are for sharing
I hate Web Components. But I love them too. I would use them again and again in any serious project. I even wrote a library in the spirit of the original Lit (a base class to be precise). So it makes me sad when I read bad things about them. Even more when somebody I fondly admire —like Rich Harris— refers to Web Components with disdain.
We have a framing problem. It might be that we’re trying to place Web Components at the same level as the rest of UI libraries —Vue, Svelte, etc., etc.—, and that’s unfair. Apples to oranges. These UI libraries solve many problems (oftentimes also create new ones) from total freedom and with an unlimited number of different techniques, like a compiler, for instance. Web Components are just, and I really mean “just”, some DOM APIs —in the most vulgar sense of the term— for adding some JavaScript logic to a custom HTML element. Namely, “upgrading” it.
Below is almost the entire “Web Components API”. (That’s probably easier and faster to learn than Stencil’s lifecycle methods alone.)
class LookMa extends HTMLElement {
static get observedAttributes() {
return [];
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = 'Yes, really!'
}
connectedCallback() {}
disconnectedCallback() {}
attributeChangedCallback(name, oldValue, newValue) {}
}
customElements.define('look-ma', LookMa);
Libraries like Lit or Stencil are a double-edged sword in this regard. Why would you choose something like Lit to build an app, with all the awkwardness of shadow DOM and the hardcore JavaScript dependency for 5.9kB, when you can get away with Preact for 4kB? To me, building a framework on top of the Web Components standards doesn’t feel right. Will connectedCallback()
be supported in browsers 30 years from now? Sure! What about lit-html
v2.2.7? Just the same as solid-js
v1.4.8. (Version numbers are irrelevant, I just want to emphasise the point.)
For the future to be even brighter, Web Components need to become HTML-first: overcoming the fact that they require JavaScript to work (thanks to @matthewcp for putting this feeling I’ve had for so long into words). But most importantly, we could take a step back and honor Web Components for the humbleness they embody.
If any given tool is not helping you solve any of your current problems, you won’t use it. Using a tool the wrong way won’t help either. So any use cases for Web Components that have to do with sharing and easy interoperability, we should actively encourage (accessible widgets, component libraries and design systems, and even dev tools). Competing with well-established UI libraries and frameworks to mostly build SPAs, not so much, or not at all.
If you disagree with all this, I will be very happy if you’d let me know.