Har*_*vay 9 abstract-syntax-tree rust codegen typescript swc-compiler
我希望在 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()),
});
}
Run Code Online (Sandbox Code Playgroud)
如何获取与programAST 对应的 TypeScript?
小智 8
您需要首先创建一个编译器(swc不带包swc_common)
在 Cargo.toml 依赖项中添加:
swc = { git = "https://github.com/swc-project/swc" }
let c = swc::Compiler::new(cm.clone());
Run Code Online (Sandbox Code Playgroud)
然后使用它暴露的打印方法
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");
Run Code Online (Sandbox Code Playgroud)
然后你可以打印该.code字段println!("{}", ast_printed.code);
| 归档时间: |
|
| 查看次数: |
1917 次 |
| 最近记录: |