Search code examples
typescriptlit

Bundling Lit components


I'm a bit about confused how I'm supposed to be referencing/importing my Lit components. The components aren't making it into my esbuild bundle, because, well, they aren't referenced.

Suppose I have ParentComponent which renders ChildComponent via <child-component>.

export class ParentComponent extends LitElement
{
    protected render(): TemplateResult
    {
        return html`<child-component></child-component>`;
    }
}

Forgive the lack of the correct Lit/web components terminology, but being a web component, I assume <child-component> is resolved at runtime, but because ChildComponent is never imported or referenced, it doesn't get included in the bundle, so <child-component> never ends up registered by Lit, and things don't work very well.

If I import ChildComponent and do something like the below, ChildComponent is bundled and things work:

protected render(): TemplateResult
{
    console.log(ChildComponent);
    return html`<child-component></child-component>`;
}

What am I supposed to be doing? How can I ensure my components are included in the bundle even though importing ChildComponent in the first example would still not have it included in the bundle because it would be unused?


Solution

  • At the entry point of your application, import all your components like this:

    import "./components/ChildComponent.js";
    import "./components/AnotherComponent.js";
    // ...
    

    Do not make it a named import if you are not going to use it:

    import ChildComponent from "./components/ChildComponent.js"; // ❌
    import { AnotherComponent } from "./components/AnotherComponent.js"; // ❌