diff --git a/docs/src/commands/build.md b/docs/src/commands/build.md
index 9b12922e..66f07fe2 100644
--- a/docs/src/commands/build.md
+++ b/docs/src/commands/build.md
@@ -138,6 +138,19 @@ example, to build the previous example using cargo's offline feature:
wasm-pack build examples/js-hello-world --mode no-install -- --offline
```
+## Passing arguments to wasm-bindgen
+
+You can forward arbitrary flags to the underlying `wasm-bindgen` CLI by repeating `--wbg-arg` (alias: `--wbg`). For example:
+
+```
+wasm-pack build --wbg-arg --experimental-reset-state-function
+wasm-pack build --wbg-arg --weak-refs --wbg-arg --reference-types
+```
+
+Notes:
+- `--wbg-arg` may be specified multiple times; each value is appended to the `wasm-bindgen` invocation.
+- If a forwarded flag conflicts with a default flag that wasm-pack sets, the later one on the command line takes effect.
+
If you need to include additional assets in the pkg
diff --git a/src/bindgen.rs b/src/bindgen.rs
index 1c0f9e9a..06a8cac7 100644
--- a/src/bindgen.rs
+++ b/src/bindgen.rs
@@ -22,6 +22,7 @@ pub fn wasm_bindgen_build(
target: Target,
profile: BuildProfile,
extra_options: &Vec,
+ bindgen_args: &[String],
) -> Result<()> {
let profile_name = match profile.clone() {
BuildProfile::Release | BuildProfile::Profiling => "release",
@@ -96,6 +97,10 @@ pub fn wasm_bindgen_build(
cmd.arg("--split-linked-modules");
}
+ for a in bindgen_args {
+ cmd.arg(a);
+ }
+
child::run(cmd, "wasm-bindgen").context("Running the wasm-bindgen CLI")?;
Ok(())
}
diff --git a/src/command/build.rs b/src/command/build.rs
index 11d3ab98..f96b675a 100644
--- a/src/command/build.rs
+++ b/src/command/build.rs
@@ -40,15 +40,17 @@ pub struct Build {
pub out_name: Option,
pub bindgen: Option,
pub cache: Cache,
+ pub bindgen_args: Vec,
pub extra_options: Vec,
}
/// What sort of output we're going to be generating and flags we're invoking
/// `wasm-bindgen` with.
-#[derive(Clone, Copy, Debug)]
+#[derive(Clone, Copy, Debug, Default)]
pub enum Target {
/// Default output mode or `--target bundler`, indicates output will be
/// used with a bundle in a later step.
+ #[default]
Bundler,
/// Correspond to `--target web` where the output is natively usable as an
/// ES module in a browser and the wasm is manually instantiated.
@@ -65,12 +67,6 @@ pub enum Target {
Deno,
}
-impl Default for Target {
- fn default() -> Target {
- Target::Bundler
- }
-}
-
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
@@ -113,7 +109,7 @@ pub enum BuildProfile {
}
/// Everything required to configure and run the `wasm-pack build` command.
-#[derive(Debug, Args)]
+#[derive(Debug, Args, Default)]
#[command(allow_hyphen_values = true, trailing_var_arg = true)]
pub struct BuildOptions {
/// The path to the Rust crate. If not set, searches up the path from the current directory.
@@ -182,34 +178,14 @@ pub struct BuildOptions {
/// Option to skip optimization with wasm-opt
pub no_opt: bool,
+ #[clap(long = "wbg-arg", visible_alias = "wbg", allow_hyphen_values = true)]
+ /// Pass an argument to wasm-bindgen. May be used multiple times.
+ pub wbg_arg: Vec,
+
/// List of extra options to pass to `cargo build`
pub extra_options: Vec,
}
-impl Default for BuildOptions {
- fn default() -> Self {
- Self {
- path: None,
- scope: None,
- mode: InstallMode::default(),
- disable_dts: false,
- weak_refs: false,
- reference_types: false,
- target: Target::default(),
- debug: false,
- dev: false,
- no_pack: false,
- no_opt: false,
- release: false,
- profiling: false,
- profile: None,
- out_dir: String::new(),
- out_name: None,
- extra_options: Vec::new(),
- }
- }
-}
-
type BuildStep = fn(&mut Build) -> Result<()>;
impl Build {
@@ -259,6 +235,7 @@ impl Build {
out_name: build_opts.out_name,
bindgen: None,
cache: cache::get_wasm_pack_cache()?,
+ bindgen_args: build_opts.wbg_arg,
extra_options: build_opts.extra_options,
})
}
@@ -445,6 +422,7 @@ impl Build {
self.target,
self.profile.clone(),
&self.extra_options,
+ &self.bindgen_args,
)?;
info!("wasm bindings were built at {:#?}.", &self.out_dir);
Ok(())
diff --git a/src/command/test.rs b/src/command/test.rs
index 74a88448..05739be4 100644
--- a/src/command/test.rs
+++ b/src/command/test.rs
@@ -120,8 +120,7 @@ impl Test {
mut path_and_extra_options,
} = test_opts;
- let first_arg_is_path = path_and_extra_options
- .get(0)
+ let first_arg_is_path = path_and_extra_options.first()
.map(|first_arg| !first_arg.starts_with("-"))
.unwrap_or(false);
@@ -295,7 +294,7 @@ impl Test {
let status = install::download_prebuilt_or_cargo_install(
Tool::WasmBindgen,
&self.cache,
- &bindgen_version,
+ bindgen_version,
self.mode.install_permitted(),
)?;
diff --git a/src/command/utils.rs b/src/command/utils.rs
index 509bc530..921b6926 100644
--- a/src/command/utils.rs
+++ b/src/command/utils.rs
@@ -53,7 +53,7 @@ pub fn find_pkg_directory(path: &Path, pkg_directory: &Path) -> Option
WalkDir::new(path)
.into_iter()
.filter_map(|x| x.ok().map(|e| e.into_path()))
- .find(|x| is_pkg_directory(&x, pkg_directory))
+ .find(|x| is_pkg_directory(x, pkg_directory))
}
fn is_pkg_directory(path: &Path, pkg_directory: &Path) -> bool {
diff --git a/src/generate.rs b/src/generate.rs
index 660f123b..2f360888 100644
--- a/src/generate.rs
+++ b/src/generate.rs
@@ -13,8 +13,8 @@ pub fn generate(template: &str, name: &str, install_status: &install::Status) ->
.binary(&Tool::CargoGenerate.to_string())?;
let mut cmd = Command::new(&bin_path);
cmd.arg("generate");
- cmd.arg("--git").arg(&template);
- cmd.arg("--name").arg(&name);
+ cmd.arg("--git").arg(template);
+ cmd.arg("--name").arg(name);
println!(
"{} Generating a new rustwasm project with name '{}'...",
diff --git a/src/install/mod.rs b/src/install/mod.rs
index b1eedfa2..3b560c2e 100644
--- a/src/install/mod.rs
+++ b/src/install/mod.rs
@@ -110,7 +110,7 @@ pub fn get_cli_version(tool: &Tool, path: &Path) -> Result {
let mut cmd = Command::new(path);
cmd.arg("--version");
let stdout = child::run_capture_stdout(cmd, tool)?;
- let version = stdout.trim().split_whitespace().nth(1);
+ let version = stdout.split_whitespace().nth(1);
match version {
Some(v) => Ok(v.to_string()),
None => bail!("Something went wrong! We couldn't determine your version of the wasm-bindgen CLI. We were supposed to set that up for you, so it's likely not your fault! You should file an issue: https://github.com/drager/wasm-pack/issues/new?template=bug_report.md.")
diff --git a/src/install/mode.rs b/src/install/mode.rs
index a55153de..d265051f 100644
--- a/src/install/mode.rs
+++ b/src/install/mode.rs
@@ -4,8 +4,10 @@ use std::str::FromStr;
/// The `InstallMode` determines which mode of initialization we are running, and
/// what install steps we perform.
#[derive(Clone, Copy, Debug)]
+#[derive(Default)]
pub enum InstallMode {
/// Perform all the install steps.
+ #[default]
Normal,
/// Don't install tools like `wasm-bindgen`, just use the global
/// environment's existing versions to do builds.
@@ -14,11 +16,6 @@ pub enum InstallMode {
Force,
}
-impl Default for InstallMode {
- fn default() -> InstallMode {
- InstallMode::Normal
- }
-}
impl FromStr for InstallMode {
type Err = Error;
diff --git a/src/installer.rs b/src/installer.rs
index 06cbafff..7cfc5be0 100644
--- a/src/installer.rs
+++ b/src/installer.rs
@@ -24,7 +24,6 @@ use std::path::Path;
use std::process;
use anyhow::{anyhow, bail, Context, Result};
-use which;
pub fn install() -> ! {
if let Err(e) = do_install() {
diff --git a/src/license.rs b/src/license.rs
index 5305e41e..94593108 100644
--- a/src/license.rs
+++ b/src/license.rs
@@ -39,12 +39,12 @@ fn glob_license_files(path: &Path) -> Result> {
/// Copy the crate's license into the `pkg` directory.
pub fn copy_from_crate(crate_data: &CrateData, path: &Path, out_dir: &Path) -> Result<()> {
assert!(
- fs::metadata(path).ok().map_or(false, |m| m.is_dir()),
+ fs::metadata(path).ok().is_some_and(|m| m.is_dir()),
"crate directory should exist"
);
assert!(
- fs::metadata(&out_dir).ok().map_or(false, |m| m.is_dir()),
+ fs::metadata(out_dir).ok().is_some_and(|m| m.is_dir()),
"crate's pkg directory should exist"
);
diff --git a/src/main.rs b/src/main.rs
index 46555f2b..bcfd5ccc 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -61,7 +61,7 @@ fn run() -> Result<()> {
let wasm_pack_version = background_check_for_updates();
// Deprecate `init`
- if let Some("init") = env::args().nth(1).as_ref().map(|arg| arg.as_str()) {
+ if let Some("init") = env::args().nth(1).as_deref() {
println!("wasm-pack init is deprecated, consider using wasm-pack build");
}
diff --git a/src/manifest/mod.rs b/src/manifest/mod.rs
index a326693a..8bbaf854 100644
--- a/src/manifest/mod.rs
+++ b/src/manifest/mod.rs
@@ -152,7 +152,7 @@ impl Crate {
match old_metadata_file {
Some(ref file_contents) => {
- let last_updated = Self::return_stamp_file_value(&file_contents, "created")
+ let last_updated = Self::return_stamp_file_value(file_contents, "created")
.and_then(|t| DateTime::parse_from_str(t.as_str(), "%+").ok());
last_updated
@@ -160,7 +160,7 @@ impl Crate {
if current_time.signed_duration_since(last_updated).num_hours() > 24 {
Self::return_api_call_result(current_time).map(Some)
} else {
- Ok(Self::return_stamp_file_value(&file_contents, "version"))
+ Ok(Self::return_stamp_file_value(file_contents, "version"))
}
})
.unwrap_or_else(|| Ok(None))
@@ -177,7 +177,7 @@ impl Crate {
// "policy" as the success. This means that the 24 hours rate limiting
// will be active regardless if the check succeeded or failed.
match version {
- Ok(ref version) => Self::override_stamp_file(current_time, Some(&version)).ok(),
+ Ok(ref version) => Self::override_stamp_file(current_time, Some(version)).ok(),
Err(_) => Self::override_stamp_file(current_time, None).ok(),
};
@@ -192,7 +192,7 @@ impl Crate {
let mut file = fs::OpenOptions::new()
.read(true)
- .write(true)
+
.append(true)
.create(true)
.open(path.with_extension("stamp"))?;
@@ -240,7 +240,7 @@ impl Crate {
.try_proxy_from_env(true)
.user_agent(&format!(
"wasm-pack/{} ({})",
- WASM_PACK_VERSION.unwrap_or_else(|| "unknown"),
+ WASM_PACK_VERSION.unwrap_or("unknown"),
WASM_PACK_REPO_URL
))
.build();
@@ -251,7 +251,7 @@ impl Crate {
let status_code = resp.status();
- if 200 <= status_code && status_code < 300 {
+ if (200..300).contains(&status_code) {
let json = resp.into_json()?;
Ok(json)
diff --git a/tests/all/build.rs b/tests/all/build.rs
index c588d6bd..23c38590 100644
--- a/tests/all/build.rs
+++ b/tests/all/build.rs
@@ -421,3 +421,26 @@ fn build_crates_with_same_names() {
.assert()
.success();
}
+
+#[test]
+fn build_forwards_wbg_arg_to_wasm_bindgen() {
+ let fixture = utils::fixture::js_hello_world();
+ fixture.install_local_wasm_bindgen();
+
+ let cmd = fixture
+ .wasm_pack()
+ .arg("build")
+ .arg("--target")
+ .arg("web")
+ .arg("--wbg-arg")
+ .arg("--this-flag-should-be-forwarded")
+ .assert()
+ .failure();
+
+ let output = String::from_utf8(cmd.get_output().stderr.clone()).unwrap();
+ assert!(
+ output.contains("--this-flag-should-be-forwarded"),
+ "stderr did not contain forwarded flag, stderr was: {}",
+ output
+ );
+}