问题
I tried the following Angular component code (in TypeScript) in ASTExplorer by choosing babylon7-7.0.0-beta.12 and babelv7-7.0.0-alpha.12 and it parses, transforms and produces the exact output:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
})
export class ListComponent implements OnInit {
data: [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5'
];
constructor() { }
ngOnInit() {
}
}
However, when I try to parse and transform the same code with same version of Babel and Babylon using Babel's transformFileSync API, I get the following error:
This experimental syntax requires enabling one of the following parser plugin(s): 'decorators, decorators2' (3:0)
1 | import { Component, OnInit } from '@angular/core';
2 |
> 3 | @Component({
| ^
So, I passed the following plugins to the API (as there were more errors):
plugins: [
['transform-decorators-legacy'],
['transform-typescript'],
['transform-class-properties']
]
But, this produces an output which is very different from the input code:
var _dec, _class;
import { Component } from '@angular/core';
export let ListComponent = (_dec = Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css']
}), _dec(_class = class ListComponent {
constructor() {
this.data = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];
}
ngOnInit() {}
}) || _class);
Would appreciate your help on identifying the root cause so that I am able to parse Angular TypeScript code and build my further transformation logic.
回答1:
To get the same output as the input, don't use any transform plugins, just babel-plugin-syntax-typescript should be sufficient.
来源:https://stackoverflow.com/questions/46920528/babels-typescript-parsing-is-not-consistent