Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 655
Sophon Aniketos Avatar asked Nov 07 '25 01:11

Sophon Aniketos


1 Answers

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

cargo build --lib --target wasm32-unknown-unknown
like image 106
Kevin Reid Avatar answered Nov 12 '25 06:11

Kevin Reid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!