typescriptwebpacklit

Lit-element dependency not being recognized by TypeScript


I have two lit elements, RootElement, and CustomElement. RootElement is imported directly into my index.html with <script type="module">, and it shows up fine. To import CustomElement, I put this in RootElement's render() method:

  render() {
    return html`<script
        type="module"
        src="./path/to/customelement.ts"
      ></script>
      <custom-element></custom-element>`;
  }

But nothing shows up in the UI. If I put an import statement at the top of my code like so:

import { CustomElement } from "./path/to/customelement.ts";

Then it shows up as "unused", which makes sense since I haven't included it in the code.

However, if I do include CustomElement somewhere in my code (for example as a single statement, CustomElement;, at the bottom of the file), then it is no longer marked as "unused" and <custom-element></custom-element> renders properly as I would have expected.

What's going on here? What do I need in my tsconfig.js to convince the transpiler this dependency is necessary without me having to provide it in a useless statement somewhere?


Solution

  • As in the handbook under Additional Import Syntax you need an import without variables:

    In this case, the import does nothing. However, all of the code in maths.ts was evaluated, which could trigger side-effects which affect other objects.

    Custom elements are registered as side-effects, so all you need is to import the module. This would look like you have it:

    import "./path/to/customelement.ts";
    

    As in this other SO question, even an unused dependency is insufficient: transpilers can remove unused variables as a courtesy, but if you specify that there are no variables to consume, then the transpiler will keep the module you import and ensure it runs before the module that imports it.