我很好奇,所以我
联系了在Babel上做了很多工作的Nicolò Ribaudo,结果发现这比我想象的要容易:您可以告诉Babel
解析 类型注释,但不是
删除它们,方法是使用TypeScript
syntax plugin(
@babel/plugin-syntax-typescript
),而不是TypeScript
preset(
@babel/preset-typescript
)。
例如,如果您想转译管道运算符的支持,您的
.babelrc
可能如下所示:
{
"plugins": [
"@babel/plugin-syntax-typescript",
[
"@babel/plugin-proposal-pipeline-operator",
{
"proposal": "minimal"
}
]
]
}
然后,如果您将此.ts
文件提供给Babel:
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);
使用管道运算符转译后,它会生成带有类型注释的输出:
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);
@babel/preset-typescript
应该允许您使用 babel 来转译 TypeScript 而不是使用tsc
。您在这方面遇到了什么问题吗? - apokryfos