Babel's TypeScript parsing is not consistent

故事扮演 提交于 2019-12-12 04:59:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!