Skip to content

cli-support: Make default_module_path optional #2519

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 16 additions & 9 deletions crates/cli-support/src/js/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -632,15 +632,16 @@ impl<'a> Context<'a> {
}
}

let default_module_path = match self.config.mode {
OutputMode::Web => format!(
"\
let default_module_path = if !self.config.omit_default_module_path {
match self.config.mode {
OutputMode::Web => format!(
"\
if (typeof input === 'undefined') {{
input = new URL('{stem}_bg.wasm', import.meta.url);
}}",
stem = self.config.stem()?
),
OutputMode::NoModules { .. } => "\
stem = self.config.stem()?
),
OutputMode::NoModules { .. } => "\
if (typeof input === 'undefined') {
let src;
if (typeof document === 'undefined') {
Expand All @@ -650,11 +651,17 @@ impl<'a> Context<'a> {
}
input = src.replace(/\\.js$/, '_bg.wasm');
}"
.to_string(),
_ => "".to_string(),
.to_string(),
_ => "".to_string(),
}
} else {
String::from("")
};

let ts = self.ts_for_init_fn(has_memory, !default_module_path.is_empty())?;
let ts = self.ts_for_init_fn(
has_memory,
!self.config.omit_default_module_path && !default_module_path.is_empty(),
)?;

// Initialize the `imports` object for all import definitions that we're
// directed to wire up.
Expand Down
7 changes: 7 additions & 0 deletions crates/cli-support/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub struct Bindgen {
keep_debug: bool,
remove_name_section: bool,
remove_producers_section: bool,
omit_default_module_path: bool,
emit_start: bool,
// Experimental support for weakrefs, an upcoming ECMAScript feature.
// Currently only enable-able through an env var.
Expand Down Expand Up @@ -115,6 +116,7 @@ impl Bindgen {
multi_value: multi_value || wasm_interface_types,
wasm_interface_types,
encode_into: EncodeInto::Test,
omit_default_module_path: true,
}
}

Expand Down Expand Up @@ -282,6 +284,11 @@ impl Bindgen {
self
}

pub fn omit_default_module_path(&mut self, omit_default_module_path: bool) -> &mut Bindgen {
self.omit_default_module_path = omit_default_module_path;
self
}

pub fn generate<P: AsRef<Path>>(&mut self, path: P) -> Result<(), Error> {
self.generate_output()?.emit(path.as_ref())
}
Expand Down
5 changes: 4 additions & 1 deletion crates/cli/src/bin/wasm-bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ Options:
--keep-debug Keep debug sections in wasm files
--remove-name-section Remove the debugging `name` section of the file
--remove-producers-section Remove the telemetry `producers` section
--omit-default-module-path Don't add WebAssembly fallback imports in generated JavaScript
--encode-into MODE Whether or not to use TextEncoder#encodeInto,
valid values are [test, always, never]
--nodejs Deprecated, use `--target nodejs`
Expand Down Expand Up @@ -66,6 +67,7 @@ struct Args {
flag_keep_debug: bool,
flag_encode_into: Option<String>,
flag_target: Option<String>,
flag_omit_default_module_path: bool,
arg_input: Option<PathBuf>,
}

Expand Down Expand Up @@ -117,7 +119,8 @@ fn rmain(args: &Args) -> Result<(), Error> {
.remove_name_section(args.flag_remove_name_section)
.remove_producers_section(args.flag_remove_producers_section)
.typescript(typescript)
.omit_imports(args.flag_omit_imports);
.omit_imports(args.flag_omit_imports)
.omit_default_module_path(args.flag_omit_default_module_path);
if let Some(true) = args.flag_weak_refs {
b.weak_refs(true);
}
Expand Down
87 changes: 87 additions & 0 deletions crates/cli/tests/wasm-bindgen/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,93 @@ fn bin_crate_works() {
.stdout("hello, world\n");
}

#[test]
fn default_module_path_target_web() {
let (mut cmd, out_dir) = Project::new("default_module_path_target_web")
.file(
"src/lib.rs",
r#"
"#,
)
.wasm_bindgen("--target web");
cmd.assert().success();
let contents = fs::read_to_string(out_dir.join("default_module_path_target_web.js")).unwrap();
assert!(contents.contains(
"\
async function init(input) {
if (typeof input === 'undefined') {
input = new URL('default_module_path_target_web_bg.wasm', import.meta.url);
}",
));
}

#[test]
fn default_module_path_target_no_modules() {
let (mut cmd, out_dir) = Project::new("default_module_path_target_no_modules")
.file(
"src/lib.rs",
r#"
"#,
)
.wasm_bindgen("--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(
"\
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');
}",
));
}

#[test]
fn omit_default_module_path_target_web() {
let (mut cmd, out_dir) = Project::new("omit_default_module_path_target_web")
.file(
"src/lib.rs",
r#"
"#,
)
.wasm_bindgen("--target web --omit-default-module-path");
cmd.assert().success();
let contents =
fs::read_to_string(out_dir.join("omit_default_module_path_target_web.js")).unwrap();
assert!(contents.contains(
"\
async function init(input) {

const imports = {};",
));
}

#[test]
fn omit_default_module_path_target_no_modules() {
let (mut cmd, out_dir) = Project::new("omit_default_module_path_target_no_modules")
.file(
"src/lib.rs",
r#"
"#,
)
.wasm_bindgen("--target no-modules --omit-default-module-path");
cmd.assert().success();
let contents =
fs::read_to_string(out_dir.join("omit_default_module_path_target_no_modules.js")).unwrap();
assert!(contents.contains(
"\
async function init(input) {

const imports = {};",
));
}

#[test]
fn empty_interface_types() {
let (mut cmd, _out_dir) = Project::new("empty_interface_types")
Expand Down
4 changes: 4 additions & 0 deletions guide/src/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,7 @@ proposal](https://github.com/webassembly/reference-types) proposal, meaning that
the WebAssembly binary will use `externref` when importing and exporting
functions that work with `JsValue`. For more information see the [documentation
about reference types](./reference-types.md).

### `--omit-default-module-path`

Don't add WebAssembly fallback imports in generated JavaScript.