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-apimyproject-libmyproject-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-liblooks like:The bindings would be implemented in
myproject-weblike:As you can see, everything is done very explicitly.
js_nameandjs_classI 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-bindgenas an opt-in a dependency in yourCargo.toml:Then you can use
cfgandcfg_attrto only enable thewasm_bindgenattributes when the feature is enabled: