Skip to content
Open
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
13 changes: 13 additions & 0 deletions docs/src/commands/build.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<hr style="font-size: 1.5em; margin-top: 2.5em"/>

<sup id="footnote-0">0</sup> If you need to include additional assets in the pkg
Expand Down
5 changes: 5 additions & 0 deletions src/bindgen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ pub fn wasm_bindgen_build(
target: Target,
profile: BuildProfile,
extra_options: &Vec<String>,
bindgen_args: &[String],
) -> Result<()> {
let profile_name = match profile.clone() {
BuildProfile::Release | BuildProfile::Profiling => "release",
Expand Down Expand Up @@ -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(())
}
Expand Down
42 changes: 10 additions & 32 deletions src/command/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,17 @@ pub struct Build {
pub out_name: Option<String>,
pub bindgen: Option<install::Status>,
pub cache: Cache,
pub bindgen_args: Vec<String>,
pub extra_options: Vec<String>,
}

/// 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.
Expand All @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<String>,

/// List of extra options to pass to `cargo build`
pub extra_options: Vec<String>,
}

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 {
Expand Down Expand Up @@ -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,
})
}
Expand Down Expand Up @@ -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(())
Expand Down
5 changes: 2 additions & 3 deletions src/command/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down Expand Up @@ -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(),
)?;

Expand Down
2 changes: 1 addition & 1 deletion src/command/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ pub fn find_pkg_directory(path: &Path, pkg_directory: &Path) -> Option<PathBuf>
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 {
Expand Down
4 changes: 2 additions & 2 deletions src/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 '{}'...",
Expand Down
2 changes: 1 addition & 1 deletion src/install/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ pub fn get_cli_version(tool: &Tool, path: &Path) -> Result<String> {
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.")
Expand Down
7 changes: 2 additions & 5 deletions src/install/mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -14,11 +16,6 @@ pub enum InstallMode {
Force,
}

impl Default for InstallMode {
fn default() -> InstallMode {
InstallMode::Normal
}
}

impl FromStr for InstallMode {
type Err = Error;
Expand Down
1 change: 0 additions & 1 deletion src/installer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
4 changes: 2 additions & 2 deletions src/license.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ fn glob_license_files(path: &Path) -> Result<Vec<String>> {
/// 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"
);

Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

Expand Down
12 changes: 6 additions & 6 deletions src/manifest/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ 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
.map(|last_updated| {
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))
Expand All @@ -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(),
};

Expand All @@ -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"))?;
Expand Down Expand Up @@ -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();
Expand All @@ -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)
Expand Down
23 changes: 23 additions & 0 deletions tests/all/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
}
Loading