Use Third-Party Web Components in LWC (Beta) In #SalesforceWinter24Release

Exciting News for Lightning web components (LWC) developers! 

You can now easily integrate third-party web components into your LWC code without the need for rewriting. 

Take advantage of the growing number of web components available and enhance your Lightning experience. 

Here's how you can do it:

1. Create custom elements: 

Custom elements are the building blocks of reusable web components. 

You can create custom elements using the customElements.define() method. 

Here's an example of a basic custom element:

customElements.define('my-custom-element', class extends HTMLElement { 
    constructor() { 
        super();
        this.attachShadow({ mode: 'closed' }).innerHTML = '<div>Custom Element Constructor</div>'; 
    }
});

2. Use lwc:external directive: 

To use a third-party web component in your LWC, simply add it to your template using the lwc:external directive. 

The third-party web component will be rendered as a native web component in your LWC template. 

Here's an example:

html
<template>
    <my-custom-element lwc:external></my-custom-element>
</template>

Please note that Lightning Web Security (LWS) must be enabled in your Salesforce org for this to work, as Lightning Locker doesn't currently support third-party web components.

You have two options for integrating third-party web components:

1. Upload as a static resource: 

You can upload the third-party web component as a static resource and load it using the loadScript method from the lightning/platformResourceLoader module. 

Then, simply add the custom element to your template using lwc:external. 

You can upload up to 5 MB per static resource, with a maximum org limit of 250 MB.

2. Add as an LWC module: 

Alternatively, you can add the third-party web component as an LWC module by providing a .js-meta.xml configuration file. 

The JavaScript file for the component should not exceed a maximum file size of 128 KB.

This beta release comes with a few known issues:

- Only a closed shadow mode is supported for third-party web components using shadow DOM. 

If the third-party web component uses an open mode, update the source to use a closed mode or find an alternative component that does.

- loadScript doesn't support ECMAScript modules. 

Only pre-bundled JavaScript files with custom elements in legacy formats like IIFE or UMD are supported.

- Third-party web components with npm dependencies, or those that require compilation and bundling, are not supported. 

Importing from npm is currently not supported.

- Third-party web components that reference elements by ID in shadow DOM are not supported. 

Use template refs instead.

Please note that Experience Builder sites currently do not support third-party web components when LWS is enabled.

1 Comments