Use ofstatic
to Access JS Objects
JavaScript modules will often export arbitrary static objects for use withtheir provided interfaces. These objects can be accessed from Rust by declaringa namedstatic
in theextern
block with an#[wasm_bindgen(thread_local_v2)]
attribute.wasm-bindgen
will bind aJsThreadLocal
for these objects, which can be cloned into aJsValue
.
These values are cached in a thread-local and are meant to bind static valuesor objects only. For getters which can change their return value or throw seehow to import getters.
For example, given the following #"#optional-statics">
Optional statics
If you expect the JavaScript value you're trying to access to not always beavailable you can useOption<T>
to handle this:
# #![allow(unused_variables)]#fn main() {extern "C" { type Crypto; #[wasm_bindgen(thread_local_v2, js_name = crypto)] static CRYPTO: Option<Crypto>;}#}
Ifcrypto
is not declared or nullish (null
orundefined
) in JavaScript,it will simply returnNone
in Rust. This will also account for namespaces: itwill returnSome(T)
only if all parts are declared and not nullish.
Static strings
Strings can be imported to avoid going throughTextDecoder/Encoder
when requiring just aJsString
. This can be useful when dealing with environments whereTextDecoder/Encoder
is not available, like in audio worklets.
# #![allow(unused_variables)]#fn main() {#[wasm_bindgen]extern "C" { #[wasm_bindgen(thread_local_v2, static_string)] static STRING: JsString = "a string literal";}#}