メインコンテンツにスキップ

@babel/plugin-transform-private-methods

情報

このプラグインは、@babel/preset-envに含まれており、ES2022に含まれています。

履歴
バージョン変更
v7.3.0プライベートアクセサー(ゲッターとセッター)のサポート
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経由

シェル
$ 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の場合、プライベートメソッドはWeakSetではなくObject.defineProperty経由で親に直接割り当てられます。これにより、Object.getOwnPropertyNamesのようなものを介して「プライベート」が漏れる可能性と引き換えに、パフォーマンスとデバッグ(通常のプロパティアクセス vs .get())が向上します。

注意

トップレベルの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;
};
ヒント

プラグインオプションの設定の詳細については、こちらをご覧ください

参考文献