JSPM

babel-plugin-transform-typescript-metadata

0.2.0
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2195067
  • Score
    100M100P100Q211858F
  • License MIT

Babel plugin to emit decorator metadata like typescript compiler

Package Exports

  • babel-plugin-transform-typescript-metadata

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (babel-plugin-transform-typescript-metadata) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

babel-plugin-transform-typescript-metadata

Travis (.com) Codecov npm

Babel plugin to emit decorator metadata like typescript compiler

Motivation

TypeScript Decorators allows advanced reflection patterns when combined with Reflect.metadata output.

Current @babel/preset-typescript implementation however just strips all types and does not emit the relative Metadata in the output code.

Since this kind of information is used extensively in libraries like Nest and TypeORM to implement advanced features like Dependency Injection, I've thought it would be awesome to be able to provide the same functionality that TypeScript compiler experimentalDecorators and emitDecoratorMetadata flags provide.

This means that code like:

import { MyService } from './MyService';
import { Configuration } from './Configuration';

@Injectable()
class AnotherService {
  @Inject()
  config: Configuration;

  constructor(private service: MyService) {}
}

will be interpreted like:

import { MyService } from './MyService';
import { Configuration } from './Configuration';

@Injectable()
@Reflect.metadata('design:paramtypes', [MyService])
class AnotherService {
  @Inject()
  @Reflect.metadata('design:type', Configuration)
  config: Configuration;

  constructor(private service: MyService) {}
}

Parameter decorators

Since decorators in typescript supports also Parameters, this plugin also provides support for them, enabling the following syntax:

@Injectable()
class Some {
  constructor(@Inject() private: SomeService);
}

This will be roughly translated to:

// ...
Inject()(Some.prototype, undefined, 0);

Installation

With npm:

npm install --dev --save babel-plugin-transform-typescript-metadata

or with Yarn:

yarn add --dev babel-plugin-transform-typescript-metadata

Usage

With .babelrc:

Note: should be placed before @babel/plugin-proposal-decorators.

{
  "plugins": [
    "babel-plugin-transform-typescript-metadata",
    ["@babel/plugin-proposal-decorators", { "legacy": true }],
    ["@babel/plugin-proposal-class-properties", { "loose": true }],
  ],
  "presets": [
    "@babel/preset-typescript"
  ]
}