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

class-static-block - 图1info

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

  1. class C {
  2. static #x = 42;
  3. static y;
  4. static {
  5. try {
  6. this.y = doSomethingWith(this.#x);
  7. } catch {
  8. this.y = "unknown";
  9. }
  10. }
  11. }

will be transformed to

JavaScript

  1. class C {
  2. static #x = 42;
  3. static y;
  4. static #_ = (() => {
  5. try {
  6. this.y = doSomethingWith(this.#x);
  7. } catch {
  8. this.y = "unknown";
  9. }
  10. })();
  11. }

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

  1. {
  2. "plugins": [
  3. "@babel/plugin-transform-class-static-block",
  4. "@babel/plugin-transform-class-properties"
  5. ]
  6. }

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-class-static-block
  1. yarn add --dev @babel/plugin-transform-class-static-block
  1. pnpm add --save-dev @babel/plugin-transform-class-static-block

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-class-static-block"]
  3. }

Via CLI

Shell

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

Via Node API

JavaScript

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

References