跳至主内容

@babel/plugin-transform-private-methods

非官方测试版翻译

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

信息

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

History
VersionChanges
v7.3.0Support private accessors (getters and setters)
v7.2.0Initial Release

示例

JavaScript
class Counter extends HTMLElement {
#xValue = 0;

get #x() {
return this.#xValue;
}
set #x(value) {
this.#xValue = value;
window.requestAnimationFrame(this.#render.bind(this));
}

#clicked() {
this.#x++;
}
}

安装

npm install @babel/plugin-transform-private-methods --save-dev

用法

通过配置文件(推荐)

无配置选项时:

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

使用配置选项时:

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

通过命令行

Shell
$ babel --plugins @babel/plugin-transform-private-methods script.js

通过 Node API

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

配置选项

loose

boolean,默认值 false

备注

loose 模式的配置设置必须@babel/plugin-transform-class-properties 保持一致。

当设置为 true 时,私有方法将通过 Object.defineProperty 直接赋值到其父对象上,而不是使用 WeakSet。 这会提升性能和调试便利性(普通属性访问 vs .get() 方法),但代价是通过 Object.getOwnPropertyNames 等方法可能泄露私有属性。

注意

请考虑迁移到顶层的 privateFieldsAsProperties 配置假设。

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

请注意,privateFieldsAsPropertiessetPublicClassFields 都必须设置为 true

以下面这段代码为例:

JavaScript
class Foo {
constructor() {
this.publicField = this.#privateMethod();
}

#privateMethod() {
return 42;
}
}

默认转换结果:

JavaScript
var Foo = function Foo() {
"use strict";

babelHelpers.classCallCheck(this, Foo);

_privateMethod.add(this);

this.publicField = babelHelpers
.classPrivateMethodGet(this, _privateMethod, _privateMethod2)
.call(this);
};

var _privateMethod = new WeakSet();

var _privateMethod2 = function _privateMethod2() {
return 42;
};

当设置 { privateFieldsAsProperties: true } 时,转换结果为:

JavaScript
var Foo = function Foo() {
"use strict";

babelHelpers.classCallCheck(this, Foo);
Object.defineProperty(this, _privateMethod, {
value: _privateMethod2,
});
this.publicField = babelHelpers
.classPrivateFieldLooseBase(this, _privateMethod)
[_privateMethod]();
};

var _privateMethod = babelHelpers.classPrivateFieldLooseKey("privateMethod");

var _privateMethod2 = function _privateMethod2() {
return 42;
};
提示

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

参考