使用Babel与Parcel构建Lit Elements时装饰器无法正常工作
问题:Lit Elements + Parcel + Babel 使用装饰器时出现「Unsupported decorator location: field」错误
错误详情
Unsupported decorator location: field
错误堆栈:
Uncaught Error: Unsupported decorator location: field at $031aa01720b926d5$export$8d623b1670eb40f4 (lit-html.ts:1915:4) at lit-html.ts:1919:1 at applyDec (index.1f978438.js:4016:71) at input.component.ts:12:39 at $fa8fc9d2c4519b52$var$_applyDecs (input.component.ts:12:38) at <static_initializer> (input.component.ts:46:1) at input.component.ts:48:1 at 7elyk (index.1f978438.js:4211:3) at newRequire (index.1f978438.js:71:24) at index.1f978438.js:122:5
关联代码
input.component.ts:
import { LitElement, html } from "lit"; import { customElement, property } from "lit/decorators"; @customElement("ajt-input") export class Input extends LitElement { @property() accessor name: string = ""; @property() accessor placeholder: string = ""; @property() accessor value: string = ""; @property() accessor type: string = "text"; @property() accessor required: boolean = false; constructor() { super(); } render() { return html` <input class="${tw`w-full outline-none rounded border focus:border-2 focus:border-primary border-black p-4`}" placeholder="Your name" type="${this.type}" name="${this.name}" value="${this.value}" placeholder="${this.placeholder}" /> `; } }
解决方案
方法1:移除accessor关键字(推荐)
Lit的@property()装饰器本身已经实现了响应式属性的绑定与更新逻辑,不需要额外添加accessor关键字。修改后的代码如下:
import { LitElement, html } from "lit"; import { customElement, property } from "lit/decorators"; @customElement("ajt-input") export class Input extends LitElement { @property() name: string = ""; @property() placeholder: string = ""; @property() value: string = ""; @property() type: string = "text"; @property({ type: Boolean }) required: boolean = false; render() { return html` <input class="${tw`w-full outline-none rounded border focus:border-2 focus:border-primary border-black p-4`}" placeholder="Your name" type="${this.type}" name="${this.name}" value="${this.value}" placeholder="${this.placeholder}" ?required="${this.required}" /> `; } }
- 注意:布尔类型属性
required需要在@property()中指定type: Boolean,模板中用?required="${this.required}"的语法绑定布尔属性,符合Web Components规范。
方法2:升级Lit版本并配置装饰器支持(若需保留accessor)
如果确实需要使用accessor(遵循最新装饰器提案),需满足以下条件:
- 将Lit版本升级至2.8.0及以上,该版本开始支持配合
accessor的装饰器写法。 - 配置Babel支持最新装饰器语法:
安装依赖:
在Babel配置文件(如npm install @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties --save-dev.babelrc)中添加:{ "plugins": [ ["@babel/plugin-proposal-decorators", { "version": "2023-07" }], ["@babel/plugin-proposal-class-properties"] ] } - 配置TypeScript支持:
在tsconfig.json中添加:{ "compilerOptions": { "experimentalDecorators": true, "useDefineForClassFields": true } }
内容的提问来源于stack exchange,提问作者Ahmad Raza
相关产品推荐
相关产品推荐

