I have a crate lib
that contains tons of structs and impls. Then I have another one called web
that will make the portability of the core lib
to the web. There is also api
in case I want the app to be server-side.
myproject-api
myproject-lib
myproject-web
What I don't want is to add all the wasm
dependencies to lib
, only in the web
project and expose parts of the main library to the web. Is it possible to #[wasm_bindgen]
the structs defined in the myproject-lib
in myproject-web
?
Not directly. The
#[wasm_bindgen]
attribute relies on being able to parse the struct and impls in order to generate the bindings. You would have to create wrapper types and functions for the attribute to bind to.Say your
myproject-lib
looks like:The bindings would be implemented in
myproject-web
like:As you can see, everything is done very explicitly.
js_name
andjs_class
I believe the more widely-used method is to add the bindings to the original library but only enabled by a feature. This avoids much duplication, is less of a headache to implement, and ensures the bindings are always in-sync.
Add a
"wasm"
feature that addswasm-bindgen
as an opt-in a dependency in yourCargo.toml
:Then you can use
cfg
andcfg_attr
to only enable thewasm_bindgen
attributes when the feature is enabled: