Decorators transform

Compile class and object decorators to ES5

Stage 2 decorators are in progress babel/babel#2645. Patches welcome!

In Babel 7, transform-decorators-legacy will be the default plugin in Stage-0.

示例

(例子出自提案)

简单的类(class)装饰器

@annotation
class MyClass { }

function annotation(target) {
   target.annotated = true;
}

类(Class)装饰器

@isTestable(true)
class MyClass { }

function isTestable(value) {
   return function decorator(target) {
      target.isTestable = value;
   }
}

类(Class)函数装饰器

class C {
  @enumerable(false)
  method() { }
}

function enumerable(value) {
  return function (target, key, descriptor) {
     descriptor.enumerable = value;
     return descriptor;
  }
}

安装

npm install --save-dev babel-plugin-transform-decorators

用法

通过 .babelrc(推荐)

.babelrc

{
  "plugins": ["transform-decorators"]
}

通过 CLI

babel --plugins transform-decorators script.js

通过 Node API

require("babel-core").transform("code", {
  plugins: ["transform-decorators"]
});

参考