【问题标题】:How can I render a Lit Element Web component using Typescript Express App?如何使用 Typescript Express App 渲染 Lit Element Web 组件?
【发布时间】:2019-11-01 15:32:35
【问题描述】:

我已经创建了一个 Typescript Express 服务器:

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;

结构

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

我尝试过托管静态文件。前任。索引.html。通过res.send('index.html'); 文件被渲染,但我无法使用脚本标签导入元素。因为返回的错误是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);

我正在使用 TSC 构建我的应用程序。我手动将我的静态文件夹复制到构建文件夹中以使用。我不确定在构建时是否有自动复制此文件夹的方法。

我的编译器是否有问题,可能会给我错误Exports is not defined 研究表明它与 CommonJs 有关,但我尝试安装但结果没有改变

tsconfig.json

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

【问题讨论】:

  • 需要使用模块系统来打包或加载JS代码。
  • @SLaks 与 webpack 或 browserify 捆绑会起作用吗?
  • 如何将元素导入到 html 中?您可能需要在其中添加type="module",捆绑只是为了与不支持模块的浏览器兼容是绝对必要的

标签: node.js typescript express tsc lit-element


【解决方案1】:

我通过使用 webpack 捆绑我的代码解决了我的问题。这允许我创建一个 Index.html 导入我的 bundle.js 文件

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2021-03-08
    • 2021-05-12
    • 2021-01-01
    相关资源
    最近更新 更多