【问题标题】:How to generating TypeScript code with SWC如何使用 SWC 生成 TypeScript 代码
【发布时间】:2022-01-26 08:48:18
【问题描述】:

我希望在 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?

【问题讨论】:

    标签: typescript rust abstract-syntax-tree codegen swc-compiler


    【解决方案1】:

    您需要先创建一个编译器(使用swc 包而不是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 字段

    【讨论】:

    • 工作就像一个魅力。谢谢!
    猜你喜欢
    • 2020-02-10
    • 2016-09-15
    • 2016-07-24
    • 1970-01-01
    • 2017-12-08
    • 2022-06-25
    • 2018-07-23
    • 2016-08-30
    • 2016-02-19
    相关资源
    最近更新 更多