I'm trying to compile a LWC to a standard web component, so that after importing it I could just use it as any standard HTML tag:

    <script type="module" src="./modules/myWebComponent.js"></script>
        <my-web-component>VS Code</my-web-component>

Compiled class would be something like this:

class MyWebComponent extends HTMLElement {

    constructor() {
        // Whatever my WC needs to do

customElements.define("my-web-component", MyWebComponent);

Basically I need the HTMLElement built from my LWC. I've seen there is a CustomElementConstructor as described here, but I'm not able to compile it so that the generated .js file has the lwc import resolved, or the CustomElementConstructor exported.

I've also tried to use Rollup as explained here but I don't want to use createElement exported from LWC, I just want the compiled file to contain an HTMLElement I could use via customElements.define() and let the browser natively resolve the web component.

1 Answer 1


Follow the setup to create the Rollup or Webpack configuration, including src/modules, src/main.js, lwc.config.json, package.json, and rollup.config.js or webpack.config.js.

Once you're all set up, notice how src/main.js reads:

import { createElement } from 'lwc';
import App from 'x/app';

const elm = createElement('x-app', { is: App });

All you have to do is replace that with:

import App from 'x/app';
customElements.define('x-app', App.CustomElementConstructor);

And then you can reference that script:

<!DOCTYPE html>
    <script type="module" src="./app.js"></script>

Make sure you define every component that you intend to use so they're all properly registered with the browser. You don't even have to call document.createElement; just having it in the HTML will render it. You can also choose to use document.createElement and thing slike Element.appendChild.

I found this by scanning the LWC source, where I found this tidbit:

 * This static getter builds a Web Component class from a LWC constructor so it can be registered
 * as a new element via customElements.define() at any given time. E.g.:
 *      import Foo from 'ns/foo';
 *      customElements.define('x-foo', Foo.CustomElementConstructor);
 *      const elm = document.createElement('x-foo');
  • Thanks ! I was close, I think I was missing the correct setup for module resolution in lwc.config.json, so import wasn't working correctly and CustomElementConstructor was undefined. Working now ! Apr 3, 2023 at 14:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .