跳至主内容

@babel/plugin-transform-class-properties

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

信息

该插件已包含在 @babel/preset-env 中,属于 ES2022 标准。

示例

以下是一个包含四个将被转换的类属性的类示例:

JavaScript
class Bork {
//Property initializer syntax
instanceProperty = "bork";
boundFunction = () => {
return this.instanceProperty;
};

//Static class properties
static staticProperty = "babelIsCool";
static staticFunction = function() {
return Bork.staticProperty;
};
}

let myBork = new Bork();

//Property initializers are not on the prototype.
console.log(myBork.__proto__.boundFunction); // > undefined

//Bound functions are bound to the class instance.
console.log(myBork.boundFunction.call(undefined)); // > "bork"

//Static function exists on the class.
console.log(Bork.staticFunction()); // > "babelIsCool"

安装

npm install --save-dev @babel/plugin-transform-class-properties

用法

通过配置文件(推荐)

无配置选项时:

babel.config.json
{
"plugins": ["@babel/plugin-transform-class-properties"]
}

使用配置选项时:

babel.config.json
{
"plugins": [["@babel/plugin-transform-class-properties", { "loose": true }]]
}

通过命令行

Shell
babel --plugins @babel/plugin-transform-class-properties script.js

通过 Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-class-properties"],
});

配置选项

loose

boolean,默认值 false

当设为 true 时,类属性将编译为赋值表达式而非使用 Object.defineProperty

注意

建议迁移到顶层的 setPublicClassFields 假设配置

babel.config.json
{
"assumptions": {
"setPublicClassFields": true
}
}

关于两种方式差异的详细解释,请参阅 定义 vs. 赋值(第五部分有要点总结)

示例

JavaScript
class Bork {
static a = "foo";
static b;

x = "bar";
y;
}

setPublicClassFieldsfalse 时,上述代码将使用 Object.defineProperty 编译为:

JavaScript
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
Object.defineProperty(this, "x", {
configurable: true,
enumerable: true,
writable: true,
value: "bar",
});
Object.defineProperty(this, "y", {
configurable: true,
enumerable: true,
writable: true,
value: void 0,
});
};

Object.defineProperty(Bork, "a", {
configurable: true,
enumerable: true,
writable: true,
value: "foo",
});
Object.defineProperty(Bork, "b", {
configurable: true,
enumerable: true,
writable: true,
value: void 0,
});

setPublicClassFields 设为 true 时,将使用赋值表达式编译:

JavaScript
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
this.x = "bar";
this.y = void 0;
};

Bork.a = "foo";
Bork.b = void 0;
提示

你可以在此处阅读更多关于配置插件选项的信息。

参考