@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").transform("code", {
  2. plugins: ["@babel/plugin-proposal-decorators"]
  3. });

Options

decoratorsBeforeExport

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

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.

When using the legacy: true mode, @babel/plugin-proposal-class-properties must be used in loose mode to support the @babel/plugin-proposal-decorators.

Wrong:

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

Right:

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

You can read more about configuring plugin options here

References