Skip to main content

@babel/plugin-transform-class-static-block

信息

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

¥This plugin is included in @babel/preset-env, in ES2022

具有静态块的类将被转换为静态私有属性,其初始化程序是封装在 IIAFE(立即调用箭头函数表达式)中的静态块。

¥A class with a static block will be transformed into a static private property, whose initializer is the static block wrapped in an IIAFE (immediate invoked arrow function expression).

示例

¥Example

JavaScript
class C {
static #x = 42;
static y;
static {
try {
this.y = doSomethingWith(this.#x);
} catch {
this.y = "unknown";
}
}
}

将转变为

¥will be transformed to

JavaScript
class C {
static #x = 42;
static y;
static #_ = (() => {
try {
this.y = doSomethingWith(this.#x);
} catch {
this.y = "unknown";
}
})();
}

因为输出代码包含私有类属性,如果你已经在使用其他类功能插件(例如 @babel/plugin-transform-class-properties),请务必将其放在其他插件之前。

¥Because the output code includes private class properties, if you are already using other class feature plugins (e.g. @babel/plugin-transform-class-properties), be sure to place it before the others.

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

安装

¥Installation

npm install --save-dev @babel/plugin-transform-class-static-block

用法

¥Usage

¥With a configuration file (Recommended)

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

通过 CLI

¥Via CLI

Shell
babel --plugins @babel/plugin-transform-class-static-block script.js

通过 Node API

¥Via Node API

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

参考

¥References