Home >Web Front-end >JS Tutorial >Caveats You May Face While Working With Web Components
Web Components have been around for a while, promising a standardized way to create reusable custom elements. It's clear that while Web Components have made significant strides, there are still several caveats that developers may face while working with them. This blog will explore 10 of these caveats.
If you're deciding whether or not to use web components in your project. It's important to consider if web components is fully supported in your framework of choice or you may run into some unpleasant caveats.
For example to use web components in Angular it's required to add CUSTOM_ELEMENTS_SCHEMA to the module import.
@NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class MyModule {}
The problem with using CUSTOM_ELEMENTS_SCHEMA is that Angular will opt out of type checking and intellisense for custom elements in the templates. (see issue)
To workaround this problem you could create an Angular wrapper component.
Here's an example of what that would look like.
@Component({ selector: 'some-web-component-wrapper', template: '<some-web-component [someProperty]="someClassProperty"></some-web-component> }) export class SomeWebComponentWrapper { @Input() someClassProperty: string; } @NgModule({ declarations: [SomeWebComponentWrapper], exports: [SomeWebComponentWrapper], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class WrapperModule {}
This works but it's not a good idea to create these manually. Since that creates a lot of maintenance and we can run into out of sync issues with the api. To make this less tedious. Both Lit (see here) and Stencil (see here) provide a cli to create these automatically. However the need to create these wrapper components in the first place is additional overhead. If the framework of your choice properly supports web components you shouldn't have to create wrapper components.
Another example is with React. Now React v19 was just released which addressed these issues. However, if you're still on v18 just note that v18 does not fully support web components. So here's a couple of issues you may face while working with web components in React v18. This is taken directly from the Lit docs.
"React assumes that all JSX properties map to HTML element attributes, and provides no way to set properties. This makes it difficult to pass complex data (like objects, arrays, or functions) to web components."
"React also assumes that all DOM events have corresponding "event properties" (onclick, onmousemove, etc), and uses those instead of calling addEventListener(). This means that to properly use more complex web components you often have to use ref() and imperative code."
For React v18 Lit recommends using their wrapper components because they fix the issues with setting the properties and listening for events for you.
Here's an example of a React wrapper component using Lit.
import React from 'react'; import { createComponent } from '@lit/react'; import { MyElement } from './my-element.js'; export const MyElementComponent = createComponent({ tagName: 'my-element', elementClass: MyElement, react: React, events: { onactivate: 'activate', onchange: 'change', }, });
Usage
<MyElementComponent active={isActive} onactivate={(e) => setIsActive(e.active)} onchange={handleChange} />
Luckily with React v19 you shouldn't need to create wrapper components anymore. Yay!
The use of Web Components in micro frontends has revealed an interesting challenge:
One significant problem is the global nature of the Custom Elements Registry:
If you're using a micro frontend and plan to use web components to reuse UI elements across each app you'll most likely run into this error.
@NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class MyModule {}
This error occurs when trying to register a custom element with a name that's already been used. This is common in micro frontends because each app in a micro frontend shares the same index.html file and each app tries to define the custom elements.
There is a proposal to address this called Scoped Custom Element Registries but there's no ETA so unfortunately you'll need to use a polyfill.
If you don't use the polyfill one workaround is to manually register the custom elements with a prefix to avoid naming conflicts.
To do this in Lit, you can avoid using the @customElement decorator which auto registers the custom element. Then add a static property for the tagName.
Before
@Component({ selector: 'some-web-component-wrapper', template: '<some-web-component [someProperty]="someClassProperty"></some-web-component> }) export class SomeWebComponentWrapper { @Input() someClassProperty: string; } @NgModule({ declarations: [SomeWebComponentWrapper], exports: [SomeWebComponentWrapper], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class WrapperModule {}
After
import React from 'react'; import { createComponent } from '@lit/react'; import { MyElement } from './my-element.js'; export const MyElementComponent = createComponent({ tagName: 'my-element', elementClass: MyElement, react: React, events: { onactivate: 'activate', onchange: 'change', }, });
Then in each app you define the custom element with a prefix of the app name.
<MyElementComponent active={isActive} onactivate={(e) => setIsActive(e.active)} onchange={handleChange} />
Then to use the custom element you would use it with the new prefix.
Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': the name "foo-bar" has already been used with this registry
This works as a quick short term solution, however you may notice it's not the best developer experience so it's recommended to use the Scoped Custom Element Registry polyfill.
The Shadow DOM, while providing encapsulation, comes with its own set of challenges:
Shadow dom works by providing encapsulation. It prevents styles from leaking out of the component. It also prevents global styles from targeting elements within the component's shadow dom. However styles from outside the component can still leak in if those styles are inherited.
Here's an example.
@customElement('simple-greeting') export class SimpleGreeting extends LitElement { render() { return html`<p>Hello world!</p>`; } }
export class SimpleGreeting extends LitElement { static tagName = 'simple-greeting'; render() { return html`<p>Hello world!</p>`; } }
When we click the
component-a
[SimpleGreeting].forEach((component) => { const newTag = `app1-${component.tagName}`; if (!customElements.get(newTag)) { customElements.define(newTag, SimpleGreeting); } });
Since the event is coming from component-b you might think that the target would be component-b or the button. However the event gets retarged so the target becomes component-a.
So if you need to know if an event came from the
@NgModule({ schemas: [CUSTOM_ELEMENTS_SCHEMA], }) export class MyModule {}
This is because the routing is handled by the browser not your framework. Frameworks need to intervene these events and handle the routing at the framework level. However because events are retargetted in the shadow dom this makes it more challenging for frameworks to do so since they don't have easy access to the anchor element.
To workaround this issue we can setup an event handler on the that will stop propagation on the event and emit a new event. The new event will need to bubble and be composed. Also in the detail we need access
to the instance which we can get from the e.currentTarget.
@Component({ selector: 'some-web-component-wrapper', template: '<some-web-component [someProperty]="someClassProperty"></some-web-component> }) export class SomeWebComponentWrapper { @Input() someClassProperty: string; } @NgModule({ declarations: [SomeWebComponentWrapper], exports: [SomeWebComponentWrapper], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class WrapperModule {}
On the consuming side you can setup a global event listener to listen for this event and handle the routing by calling framework specific routing functions.
When building out web components. You can either make the decision to slot other web components or nest them inside another. Here's an example.
slotted icon
import React from 'react'; import { createComponent } from '@lit/react'; import { MyElement } from './my-element.js'; export const MyElementComponent = createComponent({ tagName: 'my-element', elementClass: MyElement, react: React, events: { onactivate: 'activate', onchange: 'change', }, });
nested icon
<MyElementComponent active={isActive} onactivate={(e) => setIsActive(e.active)} onchange={handleChange} />
If you decide to nest the component this can make it more difficult to query the nested components. Especially if you have a QA team that needs to create end to end tests, since they'll need to target specific elements on the page.
For example to access some-icon we need to first access some-banner by grabbing it's shadowRoot then create a new query inside that shadow root.
Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': the name "foo-bar" has already been used with this registry
This may look simple but it gets increasingly more difficult the more deeply nested your components are. Also if your components are nested this can make working with tooltips more difficult. Especially if you need to target a deeply nested element so you can show the tooltip underneath it.
What I've found is that using slots makes our components smaller and more flexible which is also more maintainable. So prefer slots, avoid nesting shadow doms.
Slots provide a way to compose UI elements, but they have limitations in web components.
The ::slotted selector only applies to the direct children of a slot, limiting its usefulness in more complex scenarios.
Here's an example.
@customElement('simple-greeting') export class SimpleGreeting extends LitElement { render() { return html`<p>Hello world!</p>`; } }
export class SimpleGreeting extends LitElement { static tagName = 'simple-greeting'; render() { return html`<p>Hello world!</p>`; } }
[SimpleGreeting].forEach((component) => { const newTag = `app1-${component.tagName}`; if (!customElements.get(newTag)) { customElements.define(newTag, SimpleGreeting); } });
Web components often lag behind popular frameworks like Vue, React, Svelte and Solid in adopting new features and best practices.
This can be due to the fact that web components rely on browser implementations and standards, which can take longer to evolve compared to the rapid development cycles of modern JavaScript frameworks.
As a result, developers might find themselves waiting for certain capabilities or having to implement workarounds that are readily available in other frameworks.
Some examples of this is Lit using CSS in JS as a default option for styling. It's been known for a long time now that CSS in JS frameworks had performance issues
because they often introduced additional runtime overhead. So we started seeing newer CSS in JS frameworks that switched to a zero runtime based solutions.
Lit's CSS in JS solution is still runtime based.
Another example is with Signals. Currently the default behavior in Lit is that we add reactivity to class properties by adding the @property decorator.
However, when the property gets changed it'll trigger the entire component to re-render. With Signals only part of the component that relies on the signal will get updated.
This is more efficient for working with UIs. So efficient that there's a new proposal (TC39) to get this added to JavaScript.
Now Lit does provide a package to use Signals but it's not the default reactivity when other frameworks like Vue and Solid have already been doing this for years.
We most likely won't see Signals as the default reactivity for a few more years until signals are apart of the web standards.
Yet another example which relates to my previous caveat "9. Slotted elements are always in the dom". Rich Harris the creator of Svelte talked about this
in his blog post 5 years ago titled "Why I don't use Web Components".
He talks about how they adopted the web standards approach for how slotted content renders eagerly in Svelte v2. However, they had to move away from it
in Svelte 3 because it was such a big point of frustration for developers. They noticed that majority of the time you want the slotted content to render lazily.
I can come up with more examples such as in web components there's no easy way to pass data to slots when other frameworks like Vuejs already has support for this. But the main takeaway here is that
web components since they rely on web standards adopts features much slower than frameworks that do not rely on web standards.
By not relying on web standards we can innovate and come up with better solutions.
Web Components offer a powerful way to create reusable and encapsulated custom elements. However, as we've explored, there are several caveats and challenges that developers may face when working with them. Such as framework incompatibility, usage in micro frontends, limitations of the Shadow DOM, issues with event retargeting, slots, and slow feature adoption are all areas that require careful consideration.
Despite these challenges, the benefits of Web Components, such as true encapsulation, portability, and framework independence, make them a valuable tool in modern web development. As the ecosystem continues to evolve, we can expect to see improvements and new solutions that address these caveats.
For developers considering Web Components, it's essential to weigh these pros and cons and stay informed about the latest advancements in the field. With the right approach and understanding, Web Components can be a powerful addition to your development toolkit.
The above is the detailed content of Caveats You May Face While Working With Web Components. For more information, please follow other related articles on the PHP Chinese website!