[英]It is possible to transpile into TypeScript using Babel?
I understand that Babel now has support for TypeScript style type-annotations.我知道 Babel 现在支持 TypeScript样式类型注释。 However, it does not check the types like the TypeScript compiler does, and it removes the type annotations from the output.但是,它不会像 TypeScript 编译器那样检查类型,它会从 output 中删除类型注释。 What I would like to achieve is:我想要实现的是:
Is this possible?这可能吗?
I was curious so I pinged Nicolò Ribaudo who does a lot of work on Babel, and it turns out this is easier than I thought: You can tell Babel to parse type annotations but not remove them by using the TypeScript syntax plugin ( @babel/plugin-syntax-typescript
) but not the TypeScript preset ( @babel/preset-typescript
).我很好奇,所以我联系了Nicolò Ribaudo ,他在 Babel 上做了很多工作,事实证明这比我想象的要容易:你可以告诉 Babel解析类型注释,但不能使用TypeScript语法插件( @babel/plugin-syntax-typescript
typescript )但不是 TypeScript预设( @babel/preset-typescript
)。
For instance, if you wanted to transpile support for the pipeline operator, your .babelrc
might look like this:例如,如果您想转换对管道运算符的支持,您的.babelrc
可能如下所示:
{
"plugins": [
"@babel/plugin-syntax-typescript",
[
"@babel/plugin-proposal-pipeline-operator",
{
"proposal": "minimal"
}
]
]
}
Then if you feed Babel this .ts
file:然后如果你给 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);
...it generates this output with the pipeline operator transpiled but the type annotations still in place: ...它生成这个 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.