繁体   English   中英

可以使用 Babel 转换成 TypeScript 吗?

[英]It is possible to transpile into TypeScript using Babel?

我知道 Babel 现在支持 TypeScript样式类型注释。 但是,它不会像 TypeScript 编译器那样检查类型,它会从 output 中删除类型注释。 我想要实现的是:

  1. 使用 TypeScript 注释将 stage-0 代码转换为 vanilla TypeScript
  2. 使用 TypeScript 编译器检查类型
  3. Output JavaScript 兼容Node或浏览器

这可能吗?

我很好奇,所以我联系了Nicolò Ribaudo ,他在 Babel 上做了很多工作,事实证明这比我想象的要容易:你可以告诉 Babel解析类型注释,但不能使用TypeScript语法插件@babel/plugin-syntax-typescript typescript )但不是 TypeScript预设@babel/preset-typescript )。

例如,如果您想转换对管道运算符的支持,您的.babelrc可能如下所示:

{
  "plugins": [
    "@babel/plugin-syntax-typescript",
    [
      "@babel/plugin-proposal-pipeline-operator",
      {
        "proposal": "minimal"
      }
    ]
  ]
}

然后如果你给 Babel 这个.ts文件:

function doubleSay(str: string) {
  return str + ", " + str;
}
function capitalize(str: string) {
  return str[0].toUpperCase() + str.substring(1);
}
function exclaim(str: string) {
  return str + '!';
}

let result = "hello"
  |> doubleSay
  |> capitalize
  |> exclaim;

console.log(result);

...它生成这个 output 并转换了管道运算符,但类型注释仍然存在:

var _ref, _ref2, _hello;

function doubleSay(str: string) {
  return str + ", " + str;
}

function capitalize(str: string) {
  return str[0].toUpperCase() + str.substring(1);
}

function exclaim(str: string) {
  return str + '!';
}

let result = (_ref = (_ref2 = (_hello = "hello", doubleSay(_hello)), capitalize(_ref2)), exclaim(_ref));
console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM