diff --git a/lib/binding_web/script/build.js b/lib/binding_web/script/build.js index bb13c261..142b642c 100644 --- a/lib/binding_web/script/build.js +++ b/lib/binding_web/script/build.js @@ -15,6 +15,7 @@ await esbuild.build({ sourcesContent: true, keepNames: true, external: ['fs/*', 'fs/promises'], + resolveExtensions: ['.ts', '.js', format === 'esm' ? '.mjs' : '.cjs'], }); // Copy the generated WASM files to the appropriate spot, as esbuild doesn't "bundle" WASM files diff --git a/xtask/src/build_wasm.rs b/xtask/src/build_wasm.rs index c0b6c5e8..96309239 100644 --- a/xtask/src/build_wasm.rs +++ b/xtask/src/build_wasm.rs @@ -134,7 +134,19 @@ pub fn run_wasm(args: &BuildWasm) -> Result<()> { EXPORTED_RUNTIME_METHODS.join(",") ); - std::env::set_var("EMCC_DEBUG_SAVE", "1"); + // Clean up old files from prior runs + for file in [ + "tree-sitter.mjs", + "tree-sitter.cjs", + "tree-sitter.wasm", + "tree-sitter.wasm.map", + ] { + fs::remove_file(PathBuf::from("lib/binding_web/lib").join(file)).ok(); + } + + if !args.cjs { + emscripten_flags.extend(["-s", "EXPORT_ES6=1"]); + } #[rustfmt::skip] emscripten_flags.extend([ @@ -143,7 +155,6 @@ pub fn run_wasm(args: &BuildWasm) -> Result<()> { "-fno-exceptions", "-std=c11", "-s", "WASM=1", - "-s", "EXPORT_ES6=1", "-s", "MODULARIZE=1", "-s", "INITIAL_MEMORY=33554432", "-s", "ALLOW_MEMORY_GROWTH=1", @@ -162,7 +173,7 @@ pub fn run_wasm(args: &BuildWasm) -> Result<()> { "-I", "lib/include", "--js-library", "lib/binding_web/lib/imports.js", "--pre-js", "lib/binding_web/lib/prefix.js", - "-o", "lib/binding_web/lib/tree-sitter.js", + "-o", if args.cjs { "lib/binding_web/lib/tree-sitter.cjs" } else { "lib/binding_web/lib/tree-sitter.mjs" }, "lib/src/lib.c", "lib/binding_web/lib/tree-sitter.c", ]); diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 84825957..b02136f5 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -89,6 +89,9 @@ struct BuildWasm { /// requires `tsc` to be available. #[arg(long, short)] emit_tsd: bool, + /// Generate `CommonJS` modules instead of ES modules. + #[arg(long, short, env = "CJS")] + cjs: bool, } #[derive(Args)]