This repository has been archived on 2024-10-26. You can view files and clone it, but cannot push or open issues or pull requests.
staxman-old/build.rs
2023-11-30 10:14:32 +01:00

61 lines
1.8 KiB
Rust

use std::{
fs,
path::{Path, PathBuf},
};
use swc::config::{Options, SourceMapsConfig};
use swc_common::{
self,
errors::{ColorConfig, Handler},
sync::Lrc,
SourceMap, GLOBALS,
};
fn main() {
// Find all Typescript files (that are not type declaration)
let ts_files: Vec<_> = glob::glob(&format!("{}/**/*.ts", "static/source"))
.expect("Failed to read glob pattern")
.filter_map(|entry| entry.ok())
.filter(|entry| !entry.to_string_lossy().ends_with(".d.ts"))
.collect();
for ts_file in ts_files {
compile_file(ts_file);
}
}
fn compile_file(input: PathBuf) {
let cm: Lrc<SourceMap> = Default::default();
let handler = Handler::with_tty_emitter(ColorConfig::Auto, true, false, Some(cm.clone()));
let c = swc::Compiler::new(cm.clone());
let fm = cm
.load_file(Path::new(&input))
.expect("failed to load input typescript file");
GLOBALS.set(&Default::default(), || {
let output_path = input.with_extension("js");
let sourcemap_path = input.with_extension("js.map");
let res = c
.process_js_file(
fm,
&handler,
&Options {
swcrc: true,
filename: input.to_string_lossy().into_owned(),
output_path: Some(output_path.clone()),
source_maps: Some(SourceMapsConfig::Bool(true)),
..Default::default()
},
)
.expect("parse error");
fs::create_dir_all(output_path.parent().unwrap()).expect("failed to create parent dir");
fs::write(output_path, res.code).expect("failed to write output file");
if let Some(map) = res.map {
fs::write(sourcemap_path, map).expect("failed to write output file");
}
});
}