Babel的TypeScript解析不一致 [英] Babel's TypeScript parsing is not consistent

查看:1254
本文介绍了Babel的TypeScript解析不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过选择babylon7-7.0.0-beta.12babelv7-7.0.0-alpha.12 ASTExplorer 中尝试了以下Angular组件代码(在TypeScript中)并解析,转换并产生确切的输出:

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() {
  }

}

但是,当我尝试使用Babel的transformFileSync API使用相同版本的Babel和巴比伦解析和转换相同的代码时,出现以下错误:

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({
    | ^

因此,我将以下插件传递给了API(因为出现了更多错误):

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);

感谢您在确定根本原因方面的帮助,以便我能够解析Angular TypeScript代码并构建进一步的转换逻辑.

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.

推荐答案

要获得与输入相同的输出,请不要使用任何transform插件,只需babel-plugin-syntax-typescript就足够了.

To get the same output as the input, don't use any transform plugins, just babel-plugin-syntax-typescript should be sufficient.

这篇关于Babel的TypeScript解析不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆