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

@babel/plugin-transform-class-properties

情報

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

以下は、変換される4つのクラスプロパティを持つクラスです。

JavaScript
class Bork {
//Property initializer syntax
instanceProperty = "bork";
boundFunction = () => {
return this.instanceProperty;
};

//Static class properties
static staticProperty = "babelIsCool";
static staticFunction = function() {
return Bork.staticProperty;
};
}

let myBork = new Bork();

//Property initializers are not on the prototype.
console.log(myBork.__proto__.boundFunction); // > undefined

//Bound functions are bound to the class instance.
console.log(myBork.boundFunction.call(undefined)); // > "bork"

//Static function exists on the class.
console.log(Bork.staticFunction()); // > "babelIsCool"

インストール

npm install --save-dev @babel/plugin-transform-class-properties

使い方

オプションなし

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

オプションあり

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

CLI経由

シェル
babel --plugins @babel/plugin-transform-class-properties script.js

Node API経由

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

オプション

loose

boolean、デフォルトはfalseです。

trueの場合、クラスプロパティはObject.definePropertyの代わりに代入式を使用するようにコンパイルされます。

注意

トップレベルのsetPublicClassFieldsの前提に移行することを検討してください

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

いずれかを使用した場合の結果の説明については、定義 vs. 代入(要約はパート5)を参照してください

JavaScript
class Bork {
static a = "foo";
static b;

x = "bar";
y;
}

setPublicClassFieldsfalseの場合、上記のコードはObject.definePropertyを使用して以下のようにコンパイルされます

JavaScript
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
Object.defineProperty(this, "x", {
configurable: true,
enumerable: true,
writable: true,
value: "bar",
});
Object.defineProperty(this, "y", {
configurable: true,
enumerable: true,
writable: true,
value: void 0,
});
};

Object.defineProperty(Bork, "a", {
configurable: true,
enumerable: true,
writable: true,
value: "foo",
});
Object.defineProperty(Bork, "b", {
configurable: true,
enumerable: true,
writable: true,
value: void 0,
});

setPublicClassFieldstrueに設定されている場合、代入式を使用してコンパイルされます

JavaScript
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
this.x = "bar";
this.y = void 0;
};

Bork.a = "foo";
Bork.b = void 0;
ヒント

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

参考文献