今天我们一起来学习一下如何使用TypeScript创建Lit Element应用,如果还不熟悉什么是Lit Element,可以看一下这里。
话不多说,直接上干货。
前提条件
在开始之前,请确保你已经安装了以下软件:
- Node.js
- npm - 一般来说,安装了Node.js,npm也就顺带安装好了。
创建项目
我们使用时下最流行的Vite来创建一个新的项目,Vite是一个快速的前端构建工具,可以帮助我们快速搭建开发环境。
打开命令行,运行以下命令:
1 | npm create vite@latest my-lit-app-typescript --template vanilla-ts |
添加Lit Element组件
在src
目录下创建一个新的文件夹components
,然后在该文件夹下创建一个新的文件my-element.ts
,并添加以下代码:
1 | import { LitElement, html, css } from 'lit'; |
在上面的代码中,我们创建了一个名为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 | { |
再次运行程序,不出意外,你会遇到如下错误:
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 | { |
再次运行程序,这次页面上可以看到Hello, Philip
了,Happy Coding!