Squashing .wasm files

If I use these settings in Cargo.toml:

lto = true
opt-level = "z"

And I compile this code:

fn main() {

fn flip(a: u32, b: u32) -> (u32, u32) {
    (b, a)

Using RUSTFLAGS="-C target-feature=+multivalue" cargo build --release --target=wasm32-unknown-unknown

I end up with a file that is about 65KB. The only thing being used in the code will be flip, called directly from Javascript in a browser. The vast majority of that 65KB will be unused. (wasm-opt optimizes away about 2KB.)

How do I minimize the code size further?

  • Try adding the following to Cargo.toml:
    crate-type = ["cdylib"]
    This also avoids the need to add fn main() {}.
  • Add strip = "debuginfo" to the release profile to ensure the debuginfo for the standard library is removed. This doesn't happen by default even when not emitting debuginfo for the crate itself.
  • I think -C target-feature=+multivalue requires recompiling the standard library with it to prevent ABI incompatibilities. This requires the unstable cargo feature -Zbuild-std.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.