Search code examples
node.jstypescriptexpresstsclit-element

How can I render a Lit Element Web component using Typescript Express App?


I have created a Typescript Express Server:

src/server.ts

    import express from "express";

    import { HomeController } from "./controllers";

    const app: express.Application = express();
    const port: number = ((process.env.PORT as any) as number) || 3000;

    app.use(express.static("static"));

    app.use("/", HomeController);

    app.listen(port, () => {
      // tslint:disable-next-line:no-console
      console.log(`Listening at http://localhost:${port}/`);
    });

src/controllers/index.ts

    import { Request, Response, Router } from "express";

    const router: Router = Router();

    router.get("/", (req: Request, res: Response) => {
      res.send("Hello World");
    });

    export const HomeController: Router = router;

structure

    ├───build
    │   ├───common
    │   ├───components
    │   └───controllers
    ├───src
    │   ├───common
    │   ├───components
    │   └───controllers
    └───static
        └───images

I have tried hosting a static file. Ex. index.html. via res.send('index.html'); The file is rendered but I am unable to import the element using a script tag. As the error returned is Exports is not defined

src/components/card.ts

    import { html, LitElement } from "lit-element";

    class Card extends LitElement {
      protected render() {
        return html`
          <img src="../../static/images/AS.png" />
        `;
      }
    }

    declare global {
      interface HTMLElementTagNameMap {
        "card-element": Card;
      }
    }

    customElements.define("card-element", Card);

I am using TSC to build my application. I manually copied my static folder into by build folder to use. Im not sure if there is an automatic way to copy this folder on build.

Is there something that I am doing wrong with my compiler that may be giving me the error Exports is not defined research says its something to do with CommonJs but I tried installing and the result didnt change

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "lib": ["es6", "dom"],
    "outDir": "./build",
    "strict": true,
    "moduleResolution": "node",
    "typeRoots": ["./modules"],
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}

Solution

  • I resolved my problem by bundling my code using webpack. This allowed me to create an Index.html importing my bundle.js file