使用swc rust api转换javascript

  • 创建项目

    $ cargo new demo
  • 引入swc的依赖

    [package]
    name = "demo"
    version = "0.1.0"
    edition = "2021"
    # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
    [dependencies]
    serde_json = "1.0.66"
    serde = "1.0.127"
    swc = "0.198.0"
    swc_ecma_parser = "0.108.1"
    swc_common = {version = "0.20.1", features = ["tty-emitter", "sourcemap"]}
    swc_ecma_preset_env = "0.144.0"
  • 编写转换代码

extern crate swc_common;
extern crate swc_ecma_parser;

use std::path::Path;
use swc::config::{Config, Options};
use swc_common::sync::Lrc;
use swc_common::{
    errors::{ColorConfig, Handler},
    SourceMap,
};

fn main() {
    let input = String::from("app.js");
    swc_transform(input);
}

fn swc_transform(file: String) {
    let cm: Lrc<SourceMap> = Default::default();
    let handler =
    Handler::with_tty_emitter(ColorConfig::Auto, true, false,
        Some(cm.clone()));
    let fm = cm.load_file(Path::new(file.as_str())).expect("");
    let compiler = swc::Compiler::new(cm.clone());
    let output = compiler.process_js_file(fm.clone(), &handler, &Options {
        config: Config {
            env: None,
            test: None,
            exclude: None,
            jsc: Default::default(),
            module: None,
            minify: Default::default(),
            input_source_map: None,
            source_maps: None,
            inline_sources_content: Default::default(),
            emit_source_map_columns: Default::default(),
            error: Default::default(),
            is_module: Default::default(),
            schema: None
        },
        skip_helper_injection: false,
        disable_hygiene: false,
        disable_fixer: false,
        top_level_mark: None,
        cwd: Default::default(),
        caller: None,
        filename: file,
        config_file: None,
        root: None,
        root_mode: Default::default(),
        swcrc: false,
        swcrc_roots: None,
        env_name: "".to_string(),
        source_maps: None,
        source_file_name: None,
        source_root: None,
        output_path: None,
        experimental: Default::default()
    }).expect("transform error");
    println!("{:?}", output.code);
}

ps: 为什么不直接使用swc的node api 而非要通过rust api 存在?原因主要有以下几点:

  • 语言优势,大型项目中最好是使用强类型语言,多人维护起来方便很多
  • 打包方式,.node 文件不容易别破解

如果你喜欢我的作品,请考虑赞助,以保持它们的可持续性。

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

carog cargo

1年前 评论
schizobulia (楼主) 1年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!