How to compile to both wasm and binary in a Rust crate?

Viewed 369

I'm writing the back-end for a web application and would like to reuse some logic for client-side. I want to use wasm to generate a library which Javascript can use. Suppose the logic is in lib.rs. What should I do, so that:

  1. The back-end can import and use the code in lib.rs as normal, also cargo build generates a binary as expected.
  2. Rust generates a wasm library for lib.rs

I tried adding these to my cargo file (by following this: Rust package with both a library and a binary?):

[lib]
crate-type = ["cdylib", "rlib"]

[[bin]]
name = "mybin"
path = "src/main.rs"

But it seems like cargo is building my binary for the browser, so it is missing all the sys crate.

2 Answers

You can ask for only your library to be built using the --lib option.

cargo build --lib --target wasm32-unknown-unknown
Related