Skip to main content

@babel/plugin-transform-private-methods

info

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

历史
版本变更
v7.3.0支持私有访问器(getter 和 setter)
v7.2.0初始发布

示例​

🌐 Example

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++;
}
}

安装​

🌐 Installation

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

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

没有选项:

🌐 Without options:

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

有选项:

🌐 With options:

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

通过 CLI​

🌐 Via CLI

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

通过 Node API​

🌐 Via Node API

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

选项​

🌐 Options

loose​

boolean,默认值为 false。

note

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

当为真时,私有方法将直接通过 Object.defineProperty 分配到其父级,而不是通过 WeakSet。这会提高性能和调试(普通属性访问 vs .get()),但代价是可能通过像 Object.getOwnPropertyNames 这样的方式泄露“私有”内容。

🌐 When true, private methods will be assigned directly on its parent via Object.defineProperty rather than 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.

让我们使用以下示例:

🌐 Let's use the following as an example:

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

#privateMethod() {
return 42;
}
}

默认情况下,这变为:

🌐 By default, this becomes:

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 },它变成了:

🌐 With { privateFieldsAsProperties: true }, it becomes:

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;
};
tip

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

参考​

🌐 References