Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
4 changes: 2 additions & 2 deletions src/build/wasm_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ pub fn check_for_wasm32_target() -> Result<()> {
/// Get rustc's sysroot as a PathBuf
fn get_rustc_sysroot() -> Result<PathBuf> {
let command = Command::new("rustc")
.args(&["--print", "sysroot"])
.args(["--print", "sysroot"])
.output()?;

if command.status.success() {
Expand All @@ -84,7 +84,7 @@ fn get_rustc_sysroot() -> Result<PathBuf> {
/// Get wasm32-unknown-unknown target libdir
fn get_rustc_wasm32_unknown_unknown_target_libdir() -> Result<PathBuf> {
let command = Command::new("rustc")
.args(&[
.args([
"--target",
"wasm32-unknown-unknown",
"--print",
Expand Down
38 changes: 10 additions & 28 deletions src/command/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,18 @@ 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(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,11 +68,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 {
Expand Down Expand Up @@ -115,6 +113,7 @@ pub enum BuildProfile {
/// Everything required to configure and run the `wasm-pack build` command.
#[derive(Debug, Args)]
#[command(allow_hyphen_values = true, trailing_var_arg = true)]
#[derive(Default)]
pub struct BuildOptions {
/// The path to the Rust crate. If not set, searches up the path from the current directory.
#[clap()]
Expand Down Expand Up @@ -182,33 +181,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<()>;

Expand Down Expand Up @@ -259,6 +239,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 +426,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
4 changes: 2 additions & 2 deletions src/command/login.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ pub fn login(
&scope, &registry, &auth_type
);
info!("npm info located in the npm debug log");
npm::npm_login(&registry, &scope, &auth_type)?;
npm::npm_login(&registry, scope, auth_type)?;
info!("Logged you in!");

PBAR.info(&"👋 logged you in!".to_string());
PBAR.info("👋 logged you in!");
Ok(())
}
2 changes: 1 addition & 1 deletion src/command/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub enum Command {
/// The URL to the template
#[clap(
long = "template",
default_value = "https://github.com/drager/wasm-pack-template"
default_value = "https://github.com/rustwasm/wasm-pack-template"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
default_value = "https://github.com/rustwasm/wasm-pack-template"
default_value = "https://github.com/drager/wasm-pack-template"

)]
template: String,
#[clap(long = "mode", short = 'm', default_value = "normal")]
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
4 changes: 2 additions & 2 deletions src/command/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ fn find_manifest_from_cwd() -> Result<PathBuf> {
/// Construct our `pkg` directory in the crate.
pub fn create_pkg_dir(out_dir: &Path) -> Result<()> {
let _ = fs::remove_file(out_dir.join("package.json")); // Clean up package.json from previous runs
fs::create_dir_all(&out_dir)?;
fs::create_dir_all(out_dir)?;
fs::write(out_dir.join(".gitignore"), "*")?;
Ok(())
}
Expand All @@ -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
20 changes: 10 additions & 10 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 Expand Up @@ -473,8 +473,8 @@ impl CrateData {
}

fn is_same_path(path1: &Path, path2: &Path) -> bool {
if let Ok(path1) = fs::canonicalize(&path1) {
if let Ok(path2) = fs::canonicalize(&path2) {
if let Ok(path1) = fs::canonicalize(path1) {
if let Ok(path2) = fs::canonicalize(path2) {
return path1 == path2;
}
}
Expand All @@ -489,7 +489,7 @@ impl CrateData {
/// Will return Err if the file (manifest_path) couldn't be read or
/// if deserialize to `CargoManifest` fails.
pub fn parse_crate_data(manifest_path: &Path) -> Result<ManifestAndUnsedKeys> {
let manifest = fs::read_to_string(&manifest_path)
let manifest = fs::read_to_string(manifest_path)
.with_context(|| anyhow!("failed to read: {}", manifest_path.display()))?;
let manifest = toml::Deserializer::new(&manifest);

Expand Down Expand Up @@ -683,7 +683,7 @@ impl CrateData {
None
};

let keywords = if pkg.keywords.len() > 0 {
let keywords = if !pkg.keywords.is_empty() {
Some(pkg.keywords.clone())
} else {
None
Expand Down
2 changes: 1 addition & 1 deletion src/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub fn npm_pack(path: &str) -> Result<()> {
pub fn npm_publish(path: &str, access: Option<Access>, tag: Option<String>) -> Result<()> {
let mut cmd = child::new_command("npm");
match access {
Some(a) => cmd.current_dir(path).arg("publish").arg(&a.to_string()),
Some(a) => cmd.current_dir(path).arg("publish").arg(a.to_string()),
None => cmd.current_dir(path).arg("publish"),
};
if let Some(tag) = tag {
Expand Down
4 changes: 2 additions & 2 deletions src/readme.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ use crate::PBAR;
/// Copy the crate's README 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
Loading
Loading