Skip to content

Latest commit

 

History

History
86 lines (67 loc) · 1.74 KB

plugin-proposal-class-static-block.md

File metadata and controls

86 lines (67 loc) · 1.74 KB
Error in user YAML: (<unknown>): found character that cannot start any token while scanning for the next token at line 2 column 8
---
id: babel-plugin-proposal-class-static-block
title: @babel/plugin-proposal-class-static-block
sidebar_label: 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

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

will be transformed to

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.

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

Installation

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

Usage

With a configuration file (Recommended)

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

Via CLI

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

Via Node API

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

References