I am building a Rust web application using leptos. It is a client side rendered application, therefore I am using trunk serve to start my application.
I want to add the rand crate but this gives me an error on startup, which links to this part of the getrandom docs. (getrandom is a dependency of rand). Which states:
To enable
getrandom’s functionality onwasm32-unknown-unknownusing the Web Crypto methods described above viawasm-bindgen, do both of the following:
- Use the
wasm_jsfeature flag, i.e.getrandom = { version = "0.3", features = ["wasm_js"]}. On its own, this only makes the backend available. (As a side effect this will make yourCargo.locksignificantly larger if you are not already usingwasm-bindgen, but otherwise enabling this feature is harmless.)- Set
RUSTFLAGS='--cfg getrandom_backend="wasm_js"'(see above).
The first one was easy to do, but the second one is tricky since I am using trunk. But it does not seem possible to pass a flag to cargo build using trunk. It even says so explicitly when I encounter the build error:
error from build pipeline
Caused by:
0: HTML build pipeline failed (1 errors), showing first
1: error from asset pipeline
2: running cargo build
3: error during cargo build execution
4: cargo call to executable 'cargo' with args: '["build", "--target=wasm32-unknown-unknown", "--manifest-path", "/Users/user/git/leptos_stuff/Cargo.toml"]' returned a bad status: exit status: 101
I need trunk serve to pass RUSTFLAGS='--cfg getrandom_backend="wasm_js"' to cargo build. I have not found anything about that in the trunk docs.
I have tried the following (my shell is zsh):
RUSTFLAGS='--cfg getrandom_backend="wasm_js"' && trunk servetrunk serve --cfg getrandom_backend="wasm_js"rustflags="--cfg getrandom_backend="wasm_js"" in Trunk.toml in the build section.command="cargo build --cfg getrandom_backend=\"wasm_js\" --target=wasm32-unknown-unknown --manifest-path /Users/user/git/leptos_stuff/Cargo.toml " in Trunk.toml in the build section.I still get this error:
error: The wasm32-unknown-unknown targets are not supported by default; you may need to enable the "wasm_js" configuration flag. Note that enabling the `wasm_js` feature flag alone is insufficient. For more information see: https://docs.rs/getrandom/#webassembly-support
So I must be doing something wrong. How can I pass this flag to cargo through trunk serve?
Like @cafce25 commented, the CLI syntax would be:
RUSTFLAGS='--cfg getrandom_backend="wasm_js"' trunk serve
But if you're tired of doing it the whole time and just want to use trunk serve (and also make it easier for other people working on your project), I'd recommend adding a Cargo config.
Create a .cargo directory with config.toml inside with:
[target.wasm32-unknown-unknown]
rustflags = ["--cfg", "getrandom_backend=\"wasm_js\""]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With