Skip to main content

@babel/plugin-transform-private-property-in-object

信息

此插件包含在 @babel/preset-env 中,在 ES2022

¥This plugin is included in @babel/preset-env, in ES2022

示例

¥Example

输入

¥In

JavaScript
class Foo {
#bar = "bar";

test(obj) {
return #bar in obj;
}
}

输出

¥Out

JavaScript
class Foo {
constructor() {
_bar.set(this, {
writable: true,
value: "bar",
});
}

test() {
return _bar.has(this);
}
}

var _bar = new WeakMap();

安装

¥Installation

npm install --save-dev @babel/plugin-transform-private-property-in-object

用法

¥Usage

¥With a configuration file (Recommended)

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

通过 CLI

¥Via CLI

Shell
babel --plugins @babel/plugin-transform-private-property-in-object

通过 Node API

¥Via Node API

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

选项

¥Options

loose

boolean,默认为 false

¥boolean, defaults to false.

注意

loose 模式配置设置必须与 @babel/transform-class-properties 相同。

¥The loose mode configuration setting must be the same as @babel/transform-class-properties.

当为真时,私有属性 in 表达式将检查对象上自己的属性(而不是继承的属性),而不是检查 WeakSet 中的存在。这会提高性能和调试(与 .get() 相比,正常的属性访问),但代价是可能通过 Object.getOwnPropertyNames 之类的东西泄漏 "privates"。

¥When true, private property in expressions will check own properties (as opposed to inherited ones) on the object, instead of checking for presence inside a WeakSet. This results in improved performance and debugging (normal property access vs .get()) at the expense of potentially leaking "privates" via things like Object.getOwnPropertyNames.

提醒

考虑迁移到顶层 privateFieldsAsProperties 假设。

¥Consider migrating to the top level privateFieldsAsProperties assumption.

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

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

¥Note that both privateFieldsAsProperties and setPublicClassFields must be set to true.

示例

¥Example

输入

¥In

JavaScript
class Foo {
#bar = "bar";

test(obj) {
return #bar in obj;
}
}

输出

¥Out

JavaScript
class Foo {
constructor() {
Object.defineProperty(this, _bar, {
writable: true,
value: "bar",
});
}

test() {
return Object.prototype.hasOwnProperty.call(this, _bar);
}
}

var _bar = babelHelpers.classPrivateFieldLooseKey("bar");
提示

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

¥You can read more about configuring plugin options here

参考

¥References