@babel/plugin-transform-private-property-in-object
示例
¥Example
输入
¥In
class Foo {
#bar = "bar";
test(obj) {
return #bar in obj;
}
}
输出
¥Out
class Foo {
constructor() {
_bar.set(this, {
writable: true,
value: "bar",
});
}
test() {
return _bar.has(this);
}
}
var _bar = new WeakMap();
安装
¥Installation
- npm
- Yarn
- pnpm
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
用法
¥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
。
¥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.
{
"assumptions": {
"privateFieldsAsProperties": true,
"setPublicClassFields": true
}
}
请注意,privateFieldsAsProperties
和 setPublicClassFields
都必须设置为 true
。
¥Note that both privateFieldsAsProperties
and setPublicClassFields
must be set to true
.
示例
¥Example
输入
¥In
class Foo {
#bar = "bar";
test(obj) {
return #bar in obj;
}
}
输出
¥Out
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