@babel/plugin-transform-class-properties
資訊
此外掛程式包含在 @babel/preset-env
中,在 ES2022 中
範例
以下是具有四個類別屬性的類別,將會轉換。
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
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-class-properties
yarn add --dev @babel/plugin-transform-class-properties
pnpm add --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
Shell
babel --plugins @babel/plugin-transform-class-properties script.js
透過 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-class-properties"],
});
選項
loose
布林值
,預設為 false
。
當為 true
時,類別屬性會編譯為使用指定表達式,而不是 Object.defineProperty
。
注意
考慮遷移到頂層 setPublicClassFields
假設
babel.config.json
{
"assumptions": {
"setPublicClassFields": true
}
}
如需了解使用任一假設的後果說明,請參閱 定義相對於指定(第 5 部分中的 TL;DR)
範例
JavaScript
class Bork {
static a = "foo";
static b;
x = "bar";
y;
}
當 setPublicClassFields
為 false
時,上述程式碼將編譯成下列內容,使用 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,
});
當 setPublicClassFields
設為 true
時,它將使用指定式編譯
JavaScript
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
this.x = "bar";
this.y = void 0;
};
Bork.a = "foo";
Bork.b = void 0;
提示
您可以在 這裡進一步了解如何設定外掛選項