![](/img/trans.png)
[英]How to properly configure NextJS 12.2 w/ SWC, Jest, Eslint, and Typescript?
[英]How to generating TypeScript code with SWC
我希望在 Rust 中使用SWC來生成一些 TypeScript 代碼。 不幸的是,發射器似乎只能打印 JavaScript。 這是正確的,還是有辦法打印 TypeScript? 例如,假設我們正在制作以下 AST。
use swc_atoms::js_word;
use swc_common::{BytePos, Span, SyntaxContext};
use swc_ecmascript;
use swc_ecmascript::ast;
fn main() {
let program = ast::Program::Module(ast::Module {
body: vec![ast::ModuleItem::ModuleDecl(ast::ModuleDecl::ExportDecl(
ast::ExportDecl {
decl: ast::Decl::TsTypeAlias(ast::TsTypeAliasDecl {
span: Span::default(),
declare: false,
id: ast::Ident::new(js_word!(""), Span::default()),
type_params: None,
type_ann: Box::new(ast::TsType::TsKeywordType(ast::TsKeywordType {
span: Span::default(),
kind: ast::TsKeywordTypeKind::TsStringKeyword,
})),
}),
span: Span::default(),
},
))],
shebang: None,
span: Span::new(BytePos(1), BytePos(1), SyntaxContext::empty()),
});
}
如何獲得與program
AST 對應的 TypeScript?
您需要首先創建一個編譯器(使用swc
package 而不是swc_common
)
在 Cargo.toml 依賴項中添加:
swc = { git = "https://github.com/swc-project/swc" }
let c = swc::Compiler::new(cm.clone());
然后使用它公開的打印方法
let ast_printed = c
.print(
&ast,
Some(filename.to_str().unwrap()),
None,
false,
EsVersion::Es2022,
SourceMapsConfig::Bool(false),
&AHashMap::default(),
None,
false,
None,
)
.expect("Failed to print");
然后您可以使用println,("{}". ast_printed;code);
打印.code
字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.