codecamp

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

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

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";
}
})();
}

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

babel.config.json

{
"plugins": [
"@babel/plugin-proposal-class-static-block",
"@babel/plugin-proposal-class-properties"
]
}

Installation

  • npm
  • Yarn
  • pnpm
pnpm add --save-dev @babel/plugin-proposal-class-static-block

Usage

With a configuration file (Recommended)

babel.config.json

{
"plugins": ["@babel/plugin-proposal-class-static-block"]
}

Via CLI

Shell

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

Via Node API

JavaScript

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

References


@babel/plugin-proposal-class-properties
@babel/plugin-proposal-private-methods
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Babel 杂项

Babel 工具软件包

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }