70 %
Chris Biscardi

Compiling a single JavaScript file from Rust with swc

Assuming you have swc in your Config.toml (because it's not published) and swc_common's tty feature enabled

toml
[dependencies]
swc = { git = "https://github.com/swc-project/swc" }
[dependencies.swc_common]
git = "https://github.com/swc-project/swc"
features = ["tty-emitter"]

We can use it to pull in a JavaScript file and compile it.

rust
use std::{path::Path, sync::Arc};
use swc::{self, config::Options};
use swc_common::{
errors::{ColorConfig, Handler},
SourceMap,
};
fn main() {
let cm = Arc::<SourceMap>::default();
let handler = Arc::new(Handler::with_tty_emitter(
ColorConfig::Auto,
true,
false,
Some(cm.clone()),
));
let compiler = swc::Compiler::new(cm.clone(), handler.clone());
let fm = cm
// filepath that actually exists relative to the binary
.load_file(Path::new("src/pages/index.js"))
.expect("failed to load file");
compiler.process_js_file(
fm,
&Options {
..Default::default()
},
)
.expect("failed to process file");
}