建立專案
$ 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 協議》,轉載必須註明作者和本文連結