@babel/plugin-proposal-decorators

Example

(examples are from proposal)

Simple class decorator

  1. @annotation
  2. class MyClass {}
  3. function annotation(target) {
  4. target.annotated = true;
  5. }

Class decorator

  1. @isTestable(true)
  2. class MyClass {}
  3. function isTestable(value) {
  4. return function decorator(target) {
  5. target.isTestable = value;
  6. };
  7. }

Class function decorator

  1. class C {
  2. @enumerable(false)
  3. method() {}
  4. }
  5. function enumerable(value) {
  6. return function(target, key, descriptor) {
  7. descriptor.enumerable = value;
  8. return descriptor;
  9. };
  10. }

Installation

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

Usage

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

Via CLI

  1. babel --plugins @babel/plugin-proposal-decorators script.js

Via Node API

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

Options

History

VersionChanges
v7.17.0Added the version option with support for “2021-12”, “2018-09” and “legacy”

version

"2021-12", "2018-09" or "legacy". Defaults to "2018-09".

Selects the decorators proposal to use:

decoratorsBeforeExport

This option:

  • is disallowed when using version: "legacy";
  • is required when using version: "2018-09";
  • is optional and defaults to false when using version: "2021-12".

boolean

  1. // decoratorsBeforeExport: false
  2. export @decorator class Bar {}
  3. // decoratorsBeforeExport: true
  4. @decorator
  5. export class Foo {}

This option was added to help tc39 collect feedback from the community by allowing experimentation with both possible syntaxes.

For more information, check out: tc39/proposal-decorators#69.

legacy

⚠️ DEPRECATED: Use version: "legacy" instead. This option is a legacy alias.

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

NOTE: Compatibility with @babel/plugin-proposal-class-properties

If you are including your plugins manually and using @babel/plugin-proposal-class-properties, make sure that @babel/plugin-proposal-decorators comes before @babel/plugin-proposal-class-properties.

Wrong:

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

Right:

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

You can read more about configuring plugin options here

References