Reputation: 2441
Part of my Cargo.toml for my crate:
[features]
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?
Upvotes: 11
Views: 6878
Reputation: 191
I had the same issue.
I ended up using build.rs
to enable features when a specific target is used.
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
web-sys = { version = "0.3.64", features = ["Storage", "Window", "console"] }
[features]
sqlite = ["dep:rusqlite", "dbson/rusqlite"]
gui = []
default = ["gui"]
wasm = []
build.rs
pub fn main() {
if std::env::var("TARGET").expect("Unable to get TARGET").contains("wasm32") {
println!("cargo:rustc-cfg=feature=\"wasm\"");
}
}
Here I wanted to enable wasm
feature when the target is wasm32-unknown-unknown.
Note that this is not supported by cargo and this is run after dependency resolution.
So If I made web-sys
optional and used wasm = ["dep:web-sys"]
as a feature that wouldn't work.
Upvotes: 1
Reputation: 42849
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"]
Upvotes: 10