Skip to main content

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

info

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

示例​

🌐 Example

在

JavaScript
class Foo {
#bar = "bar";

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

出

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。

note

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

当为 true 时,私有属性 in 表达式将检查对象自身的属性(而不是继承的属性),而不是检查是否存在于 WeakSet 中。这会提升性能和调试体验(普通属性访问 vs .get()),但代价是可能通过像 Object.getOwnPropertyNames 这样的方式泄露“私有”属性。

🌐 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.

caution

考虑迁移到顶层 privateFieldsAsProperties 假设。

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

注意,privateFieldsAsProperties 和 setPublicClassFields 都必须设置为 true。

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

示例​

🌐 Example

在

JavaScript
class Foo {
#bar = "bar";

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

出

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");
tip

你可以在这里了解更多关于配置插件选项的内容

参考​

🌐 References