0%

如何使用TypeScript创建Lit Element应用

今天我们一起来学习一下如何使用TypeScript创建Lit Element应用,如果还不熟悉什么是Lit Element,可以看一下这里

话不多说,直接上干货。

前提条件

在开始之前,请确保你已经安装了以下软件:

  • Node.js
  • npm - 一般来说,安装了Node.js,npm也就顺带安装好了。

创建项目

我们使用时下最流行的Vite来创建一个新的项目,Vite是一个快速的前端构建工具,可以帮助我们快速搭建开发环境。

打开命令行,运行以下命令:

1
2
3
4
npm create vite@latest my-lit-app-typescript --template vanilla-ts
cd my-lit-app-typescript
npm install
npm install lit

添加Lit Element组件

src目录下创建一个新的文件夹components,然后在该文件夹下创建一个新的文件my-element.ts,并添加以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { LitElement, html, css } from 'lit';
import { customElement } from 'lit/decorators.js';
import { property } from 'lit/decorators.js';

@customElement('my-element')
export class MyElement extends LitElement {
@property({ type: String }) name = 'World';

static styles = css`
h1 {
color: blue;
}
`;

render() {
return html`<h1>Hello, ${this.name}!</h1>`;
}
}

在上面的代码中,我们创建了一个名为my-element的自定义元素,它继承自LitElement。我们使用了@customElement装饰器来定义这个元素,并使用@property装饰器来定义一个属性name

运行项目

使用VSCode打开项目,运行以下命令启动开发服务器:

1
npm run dev

不出意外,你会遇到@customElement("my-element")无法识别的错误:

1
Uncaught SyntaxError: Invalid or unexpected token (at my-element.ts:3:1)

这是因为@customElement是装饰器语法,这个语法还未被浏览器正式支持,目前处于state 3,在未来的版本中可以支持,所以暂时需要在tsconfig.json中添"experimentalDecorators": true配置才行。关于Decorator的更多信息,可以看这里

1
2
3
4
5
6
7
{
"compilerOptions": {
// ...
"experimentalDecorators": true,
// ...
}
}

再次运行程序,不出意外,你会遇到如下错误:

1
following properties on element my-element will not trigger updates as expected because they are set using class fields: name. Native class fields and some compiled output will overwrite accessors used for detecting changes. See https://lit.dev/msg/class-field-shadowing for more information

只需要在tsconfig.json中添加如下配置即可:

1
2
3
4
5
6
7
{
"compilerOptions": {
// ...
"useDefineForClassFields": false
// ...
}
}

再次运行程序,这次页面上可以看到Hello, Philip了,Happy Coding!