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/scripts")) .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 = 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"); } }); }