跳至主要內容

@babel/plugin-transform-private-methods

資訊

此外掛程式包含在 @babel/preset-env 中,在 ES2022

歷史記錄
版本變更
v7.3.0支援私有存取器 (getter 和 setter)
v7.2.0初始版本

範例

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

安裝

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

使用

無選項

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

有選項

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

透過 CLI

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

透過 Node API

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

選項

loose

boolean,預設為 false

注意事項

loose 模式設定 必須@babel/plugin-transform-class-properties 相同。

如果為 true,私有方法會透過 Object.defineProperty 直接指定在父類上,而不是 WeakSet。這會改善效能和除錯(一般屬性存取相對於 .get()),但可能會透過 Object.getOwnPropertyNames 等方式洩漏「私有」資料。

注意

考慮移轉到頂層 privateFieldsAsProperties 假設。

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

請注意,privateFieldsAsPropertiessetPublicClassFields 都必須設為 true

我們使用以下內容作為範例

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

#privateMethod() {
return 42;
}
}

預設情況下,這會變成

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 },會變成

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;
};
提示

您可以在 這裡進一步了解如何設定外掛選項。

參考資料