@babel/plugin-proposal-decorators · Babel (original) (raw)

Example

Simple class decorator

JavaScript


@annotation

class MyClass {}

function annotation(target) {

  target.annotated = true;

}

Class decorator

JavaScript


@isTestable(true)

class MyClass {}

function isTestable(value) {

  return function decorator(target) {

    target.isTestable = value;

  };

}

Class method decorator

JavaScript


class C {

  message = "hello!";

  @bound

  m() {

    console.log(this.message);

  }

}

function bound(value, { name, addInitializer }) {

  addInitializer(function () {

    this[name] = this[name].bind(this);

  });

}

Installation


npm install --save-dev @babel/plugin-proposal-decorators

Usage

babel.config.json


{

  "plugins": [

    ["@babel/plugin-proposal-decorators", { "version": "2023-11" }]

  ]

}

Via Node API

JavaScript


require("@babel/core").transformSync("code", {

  plugins: [

    ["@babel/plugin-proposal-decorators", { version: "2023-11" }],

  ]

});

Options

History

Version Changes
v7.24.0 Added support for version: "2023-11"
v7.22.0 Added support for version: "2023-05"
v7.21.0 Added support for version: "2023-01"
v7.19.0 Added support for version: "2022-03"
v7.17.0 Added the version option with support for "2021-12", "2018-09" and "legacy"

version

"2023-11" or "legacy".

Selects the decorators proposal to use:

When using decorators which either access or modify the metadata in the decorator context, you need to use Symbol.metadata. When Symbol.metadata is not available, Babel defaults to Symbol.for("Symbol.metadata"): this may be incompatible with other packages that use a different fallback.

To ensure that Symbol.metadata is available globally and matches the symbol used by the Babel decorators plugin during transpilation, you will need to either include a polyfill that defines it, or define it yourself:

symbol-metadata-polyfill.js


Symbol.metadata = Symbol.for("Symbol.metadata");

You can also use a third-party polyfill, such as core-js/proposals/decorator-metadata-v2.js. Make sure that the polyfill is executed before any code that uses decorators or accesses Symbol.metadata.

References