I'm compiling a set of libraries as dependencies to a WASM library, using the "raw"
wasm32-unknown-unknown target ("raw" in the sense that I don't use wasm-bindgen or wasm-pack or anything).
That works great until one of the libraries needs the
rand crate, or more specifically the
getrandom crate. I already found out that I need to enable the
js feature for
getrandom, but as soon as I do that, I can't instantiate my WebAssembly library anymore.
The error message I get in the console is:
TypeError: WebAssembly.instantiate(): Imports argument must be present and must be an object
It seems like activating this feature leads to wasm-bindgen being used in some form or another ? Does that mean that I can only use it in conjuction with wasm-bindgen, not with a "raw" library ?
You can not get randomness on the "raw" target without additional information about enviroment. The
js feature assumes that you use wasm-bingen and it's one of the reasons why it's disabled by default. If you don't want to rely on wasm-bingen, then you should use the
custom feature to provide custom randomness source specific to your environment.
Oooh ok, thanks for the hint ! I saw that the documentation mentions the
wasm-bindgen toolchain, but I wasn't aware that it's exclusive to that toolchain ...
It means you need to make a PR to that upstream library so it exposes a
js feature which will enable
getrandom/js in turn.
At a previous company, we would implement
getrandom's custom handler by importing some sort of of
fn gen_random(buffer: &mut [u8]) function from the host so the application could fill your buffer with randomness (example).
Such approach is not recommended.
getrandom docs are pretty clear about it:
This feature should only be enabled for binary, test, or benchmark crates. Library crates should generally not enable this feature, leaving such a decision to users of their library. Also, libraries should not introduce their own
js features just to enable
getrandom goes to a great length to support non-JS WASM applications.