Enable a Cargo feature by default when the target arch is WASM?

Part of my Cargo.toml for my crate:

wasm = ["ed25519-dalek/nightly", "rand/wasm-bindgen", "js-sys"]

This works, when the crate is used in another project, and the "wasm" feature is explicitly chosen.

I want to automatically enable this feature only when the target arch is WASM. I tried adding this:

#[cfg(target_arch = "wasm32")]
default = ["wasm"]

When I compile for a target other than WASM, "wasm" is included as the default, how can I make "wasm" the default only when the target is WASM?


  • You can only have target-specific dependencies, not target-specific features. This is a known bug that is unfortunately opened since 2015.

    People expects this syntax to be supported, but right now there is nothing scheduled to make this work:

    [target.'cfg(target_arch = "wasm32")'.features]
    default = ["ed25519-dalek/nightly", "rand/wasm-bindgen", "js-sys"]

    As a ugly workaround, you can create another crate that depends on your crate and let the user use this new crate:

    [target.'cfg(target_arch = "wasm32")'.dependencies.your_crate]
    version = "1.0.0"
    features = ["wasm"]