@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

  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

  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-proposal-class-properties), be sure to place it before the others.

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

Installation

  1. npm install --save-dev @babel/plugin-proposal-class-static-block

Usage

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

Via CLI

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

Via Node API

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

References