Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created March 26, 2015 16:21
Show Gist options
  • Save shuhei/4027b9c54e7ea8b3cd42 to your computer and use it in GitHub Desktop.
Save shuhei/4027b9c54e7ea8b3cd42 to your computer and use it in GitHub Desktop.
Angular 2 type annotation with babel (babel --experimental with experimental branch)
class HelloComponent {
constructor(foo: Foo, bar: Bar) { }
}
"use strict";
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
var HelloComponent = function HelloComponent(foo, bar) {
_classCallCheck(this, HelloComponent);
};
HelloComponent.parameters = [[Foo], [Bar]];
var babel = require('./babel/lib/babel/api/node');
(function () {
var t = require('./babel/lib/babel/types');
var File = require('./babel/lib/babel/transformation/file');
var Transformer = require('./babel/lib/babel/transformation/transformer');
var key = 'angular2.typeAnnotation';
var rawTransformer = {
check: t.isClass,
ClassDeclaration: function ClassDeclaration(node, parent, scope, file) {
var classRef = node.id;
var className = classRef.name;
var classBody = node.body.body;
var annotations = [];
classBody.forEach(function (bodyNode) {
if (bodyNode.type === 'MethodDefinition' && bodyNode.kind === 'constructor') {
var params = bodyNode.value.params;
params.forEach(function (param) {
var annotation = param.typeAnnotation && param.typeAnnotation.typeAnnotation.id.name;
annotations.push(annotation);
});
}
});
var params = t.arrayExpression(annotations.map(function (annotation) {
return t.arrayExpression([t.identifier(annotation)]);
}));
var propertyName = t.memberExpression(classRef, t.identifier('parameters'), false);
var assignment = t.expressionStatement(t.assignmentExpression('=', propertyName, params));
return [node, assignment];
}
};
var transformer = new Transformer(key, rawTransformer, {});
File.prototype.buildPlugins = function buildPlugins(stack) {
var pass = transformer.buildPass(this);
stack.push(pass);
};
})();
var code = [
'class HelloComponent {',
' constructor(foo: Foo, bar: Bar) { }',
'}'
].join('\n');
var result = babel.transform(code);
console.log('--- Before ---');
console.log(code);
console.log('--- After ---');
console.log(result.code);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment