首页 > 解决方案 > 聚合物未使用聚合物服务加载 ts Web 组件

问题描述

遵循此处的 LitElement 指南: https ://lit-element.polymer-project.org/guide/start

我实际上是按照书籍来跟踪它,然后 polymer serve在项目的根目录中运行。

我什至从他们的示例 stackblitz 页面复制/粘贴了每个文件。我不应该使用聚合物服务或其他东西吗?

我得到的只是空白页,它似乎无法识别 customElement

在我的元素下没有创建任何内容

我的元素.ts:

import { LitElement, html, customElement, property } from 'lit-element';

@customElement('my-element')
export class MyElement extends LitElement {
  @property()
  foo = 'foo';

  render() {
    return html`
      <p>hi!</p>
    `;
  }
}

索引.ts:

import './my-element.ts';

索引.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <script src="/node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js"></script>
    <script src="/node_modules/@webcomponents/webcomponentsjs/webcomponents-bundle.js"></script>

    <title>lit-element code sample</title>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>

包.json:

{
  "name": "my-app",
  "version": "1.0.0",
  "license": "ISC",
  "dependencies": {
    "@webcomponents/webcomponentsjs": "^2.2.10",
    "lit-element": "^2.1.0"
  }
}

标签: javascripttypescriptpolymerweb-componentlit-element

解决方案


我什至从他们的示例 stackblitz 页面复制/粘贴了每个文件

实际上 Stackblitz TS 项目遵循一个特定的结构,在该结构中index.ts被视为 TypeScript 代码的入口点,在最终结果中自动编译和导入。

本地场景完全不同:您必须选择一个构建工具来编译 TS 文件并将结果导入index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... -->
    <!-- This may differ depending on your build configuration -->
    <script src="./path/to/my-element.js" type="module"></script>
  </head>
  <body>
    <my-element></my-element>
  </body>
</html>

您可以tsc直接使用或使用模块捆绑器,例如Webpack + ts-loaderRollup + rollup-plugin-typescript2。这实际上取决于您的项目的复杂性和要求以及您想要支持的浏览器。


推荐阅读