@babel/plugin-proposal-decorators
示例
🌐 Example
简单类装饰器
🌐 Simple class decorator
@annotation
class MyClass {}
function annotation(target) {
target.annotated = true;
}
类装饰器
🌐 Class decorator
@isTestable(true)
class MyClass {}
function isTestable(value) {
return function decorator(target) {
target.isTestable = value;
};
}
类方法装饰器
🌐 Class method decorator
class C {
message = "hello!";
@bound
m() {
console.log(this.message);
}
}
function bound(value, { name, addInitializer }) {
addInitializer(function () {
this[name] = this[name].bind(this);
});
}
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-proposal-decorators
yarn add --dev @babel/plugin-proposal-decorators
pnpm add --save-dev @babel/plugin-proposal-decorators
bun add --dev @babel/plugin-proposal-decorators
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"plugins": [
["@babel/plugin-proposal-decorators", { "version": "2023-11" }]
]
}
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: [
["@babel/plugin-proposal-decorators", { version: "2023-11" }],
]
});
选项
🌐 Options
历史
| 版本 | 变更 |
|---|---|
v7.24.0 | 添加了对 version: "2023-11" 的支持 |
v7.22.0 | 添加了对 version: "2023-05" 的支持 |
v7.21.0 | 添加了对 version: "2023-01" 的支持 |
v7.19.0 | 添加了对 version: "2022-03" 的支持 |
v7.17.0 | 添加了 version 选项,并支持 "2021-12"、"2018-09" 和 "legacy" |
version
"2023-11" 或 "legacy"。
选择要使用的装饰器提案:
🌐 Selects the decorators proposal to use:
"2023-11"是在 2023 年 11 月 TC39 会议达成共识后的更新提案版本。如果它最终成为正式版本,将默认启用。它允许在export前或后使用装饰器。legacy是传统的第 1 阶段提案,定义在wycats/javascript-decorators@e1bf8d41bf。传统模式不会有功能更新,并且已知 Babel 和 TypeScript 之间存在差异。建议迁移到"2023-11"提案版本。
这个规范仓库提供了这些版本之间差异的简要总结。
🌐 The spec repo provides a brief summary of the differences between these versions.
Symbol.metadata 注意
🌐 Symbol.metadata notes
在使用装饰器时,如果装饰器会访问或修改装饰器上下文中的元数据,你需要使用 Symbol.metadata。当 Symbol.metadata 不可用时,Babel 会默认使用 Symbol.for("Symbol.metadata"):这可能与使用不同回退方案的其他包不兼容。
🌐 When using decorators which either access or modify the metadata in the decorator context, you need to use Symbol.metadata. When Symbol.metadata is not available, Babel defaults to Symbol.for("Symbol.metadata"): this may be incompatible with other packages that use a different fallback.
为了确保 Symbol.metadata 在全局可用,并且与 Babel 装饰器插件在转译时使用的符号匹配,你需要么引入一个定义它的 polyfill,要么自己定义它:
🌐 To ensure that Symbol.metadata is available globally and matches the symbol used by the Babel decorators plugin during transpilation, you will need to either include a polyfill that defines it, or define it yourself:
Symbol.metadata = Symbol.for("Symbol.metadata");
你也可以使用第三方 polyfill,比如 core-js/proposals/decorator-metadata-v2.js。确保在任何使用装饰器或访问 Symbol.metadata 的代码之前执行这个 polyfill。
🌐 You can also use a third-party polyfill, such as core-js/proposals/decorator-metadata-v2.js. Make sure that the polyfill is executed before any code that uses decorators or accesses Symbol.metadata.
参考
🌐 References