@babel/plugin-transform-class-static-block
信息
此插件包含在 @babel/preset-env
中,属于 ES2022 规范。
具有静态块的类将被转换为静态私有属性,其初始化程序是包装在 IIAFE(立即调用箭头函数表达式)中的静态块。
示例
JavaScript
class C {
static #x = 42;
static y;
static {
try {
this.y = doSomethingWith(this.#x);
} catch {
this.y = "unknown";
}
}
}
将被转换为
JavaScript
class C {
static #x = 42;
static y;
static #_ = (() => {
try {
this.y = doSomethingWith(this.#x);
} catch {
this.y = "unknown";
}
})();
}
由于输出代码包含私有类属性,如果您已经在使用其他类特性插件(例如 @babel/plugin-transform-class-properties
),请确保将其放置在其他插件*之前*。
babel.config.json
{
"plugins": [
"@babel/plugin-transform-class-static-block",
"@babel/plugin-transform-class-properties"
]
}
安装
- npm
- Yarn
- pnpm
npm install --save-dev @babel/plugin-transform-class-static-block
yarn add --dev @babel/plugin-transform-class-static-block
pnpm add --save-dev @babel/plugin-transform-class-static-block
用法
使用配置文件(推荐)
babel.config.json
{
"plugins": ["@babel/plugin-transform-class-static-block"]
}
通过 CLI
Shell
babel --plugins @babel/plugin-transform-class-static-block script.js
通过 Node API
JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-class-static-block"],
});