@babel/plugin-transform-private-property-in-object
这个插件包含在 @babel/preset-env 中,在 ES2022
示例
🌐 Example
在
class Foo {
#bar = "bar";
test(obj) {
return #bar in obj;
}
}
出
class Foo {
constructor() {
_bar.set(this, {
writable: true,
value: "bar",
});
}
test() {
return _bar.has(this);
}
}
var _bar = new WeakMap();
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-private-property-in-object
yarn add --dev @babel/plugin-transform-private-property-in-object
pnpm add --save-dev @babel/plugin-transform-private-property-in-object
bun add --dev @babel/plugin-transform-private-property-in-object
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-private-property-in-object"]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-private-property-in-object
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-private-property-in-object"],
});
选项
🌐 Options
loose
boolean,默认值为 false。
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.
考虑迁移到顶层 privateFieldsAsProperties 假设。
{
"assumptions": {
"privateFieldsAsProperties": true,
"setPublicClassFields": true
}
}
注意,privateFieldsAsProperties 和 setPublicClassFields 都必须设置为 true。
🌐 Note that both privateFieldsAsProperties and setPublicClassFields must be set to true.
示例
🌐 Example
在
class Foo {
#bar = "bar";
test(obj) {
return #bar in obj;
}
}
出
class Foo {
constructor() {
Object.defineProperty(this, _bar, {
writable: true,
value: "bar",
});
}
test() {
return Object.prototype.hasOwnProperty.call(this, _bar);
}
}
var _bar = babelHelpers.classPrivateFieldLooseKey("bar");
你可以在这里了解更多关于配置插件选项的内容
参考
🌐 References