diff --git a/crates/cli-support/src/js/mod.rs b/crates/cli-support/src/js/mod.rs index 9ee154cca1e..c697a52ba05 100644 --- a/crates/cli-support/src/js/mod.rs +++ b/crates/cli-support/src/js/mod.rs @@ -378,6 +378,15 @@ impl<'a> Context<'a> { // function. OutputMode::NoModules { global } => { js.push_str("const __exports = {};\n"); + js.push_str("let script_src;\n"); + js.push_str( + "\ + if (typeof document === 'undefined') { + script_src = location.href; + } else { + script_src = document.currentScript.src; + }\n", + ); js.push_str("let wasm;\n"); init = self.gen_init(needs_manual_start, None)?; footer.push_str(&format!( @@ -712,13 +721,7 @@ impl<'a> Context<'a> { ), OutputMode::NoModules { .. } => "\ if (typeof input === 'undefined') { - let src; - if (typeof document === 'undefined') { - src = location.href; - } else { - src = document.currentScript.src; - } - input = src.replace(/\\.js$/, '_bg.wasm'); + input = script_src.replace(/\\.js$/, '_bg.wasm'); }" .to_string(), _ => "".to_string(), diff --git a/crates/cli/tests/wasm-bindgen/main.rs b/crates/cli/tests/wasm-bindgen/main.rs index b52f14e64c3..1fb94f7c97b 100644 --- a/crates/cli/tests/wasm-bindgen/main.rs +++ b/crates/cli/tests/wasm-bindgen/main.rs @@ -258,17 +258,19 @@ fn default_module_path_target_no_modules() { cmd.assert().success(); let contents = fs::read_to_string(out_dir.join("default_module_path_target_no_modules.js")).unwrap(); + assert!(contents.contains( + "\ + if (typeof document === 'undefined') { + script_src = location.href; + } else { + script_src = document.currentScript.src; + }", + )); assert!(contents.contains( "\ async function init(input) { if (typeof input === 'undefined') { - let src; - if (typeof document === 'undefined') { - src = location.href; - } else { - src = document.currentScript.src; - } - input = src.replace(/\\.js$/, '_bg.wasm'); + input = script_src.replace(/\\.js$/, '_bg.wasm'); }", )); }