Writing examples that run natively and on WASM

I'm working on a sound library. This library shall be used as native compilation and as WASM running in a browser.

I provided an example (runnable with cargo run --example=name) which works fine.
Is there a way to modify that example to work in an WASM environment as well?

When targeting WASM the required packages are completely different and I don't know how to integrate that in my Cargo.toml (see https://github.com/RustAudio/cpal/blob/master/examples/wasm-beep/Cargo.toml for an example)
Where would I have to place the html and js files for those examples?

If there's no (easy) solution I'll fall back to using some dedicated example crates.

Here is one option that allows a feature to gate the dependencies

wasm = ["cpal/wasm-bindgen", "wasm-bindgen", "wee_alloc", "web-sys" ]

cpal = { path = "../.." }
wasm-bindgen = { version = "0.2.45", optional = true }
wee_alloc = { version = "0.4.2", optional = true }

version = "0.3.22"
features = ["console"]
optional = true 

Thank you, but where do I have to place that to make it work for example code only?
I don't want to add those dependencies to my main crate.

If you can live with users running:

cargo run --package <example_name>

instead of

cargo run --example <example_name>

Then what you can do is:

  • Put all examples separate $repository/examples/example_name/ directories

  • Each example has its own Cargo.toml as though it's a regular crate

  • Declare the top level crate as a workspace, and include the examples as members:

    # Cargo.toml
    members = ["examples/*"]

I've got a project that does this -- examples run natively with non-wasm dependencies, and on WASM with those dependencies, and the wasm dependencies aren't part of the library.

Repository: https://github.com/azriel91/nginee
Example: https://nginee.rs/examples/event_loop_console.html

1 Like

Thanks, that project is already part of a workspace. I could add those examples as prefixed package. Like "example-beep". That could be a useful work-around.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.