babel-plugin-decorator-metadata

Define decorator metadata

Downloads in past

Stats

StarsIssuesVersionUpdatedCreatedSize
babel-plugin-decorator-metadata
2360.3.07 years ago7 years agoMinified + gzip package size for babel-plugin-decorator-metadata in KB

Readme

babel-plugin-decorator-metadata Build Status Coverage Status
This plugin generates code to define metadata for decorators.

Usage

If you run the plugin on the following input
@ClassDecorator('name')
class MyClass {
  @FieldDecorator()
  field;

  @MethodDecorator()
  method() {
  }
}

it will modify the file to look like this:
@ClassDecorator('name')
class MyClass {
   /* ... */
}

Reflect.defineMetadata('decorated', ['field', 'method'], MyClass);
Reflect.defineMetadata('decorator', [{
  type: ClassDecorator,
  parameters: ['name']
}], MyClass);
Reflect.defineMetadata('decorator', [{
  type: FieldDecorator,
  parameters: []
}], MyClass, 'field');
Reflect.defineMetadata('decorator', [{
  type: MethodDecorator,
  parameters: []
}], MyClass, 'method');

Since the reflection API is still just a proposal at this time, you'll need a polyfill like core-js.
Then you can query the metadata:
const classMD = Reflect.getMetadata('decorator', MyClass);
  // { type: ClassDecorator, parameters: ['name'] }
const methodMD = Reflect.getMetadata('decorator', MyClass, 'method');
  // { type: MethodDecorator, parameters: [] }

Get Started

Install the plugin:
npm install babel-plugin-decorator-metadata --save-dev

And add the additional step to your .babelrc:
{
  "plugins": [
    "babel-plugin-syntax-decorators",
    "babel-plugin-decorator-metadata"
  ]
}

Important: Make sure to load the required polyfill (like core-js/es7/reflect from core-js) before you load any decorated class since they all require the global Reflect object.

Limitations

The plugin will only add metadata for annotated classes, methods and fields; not for accessors.