3

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.

Gnut
  • 541
  • 1
  • 5
  • 19

2 Answers2

2

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

cargo build --lib --target wasm32-unknown-unknown
Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
  • Thank you. Is there a way to specify different compile target for bin and lib in the toml file, so that `cargo build` will build both? – Gnut Nov 22 '21 at 05:24
  • @Gnut Not that I know of — a single `cargo build` command only ever builds for one target. – Kevin Reid Nov 22 '21 at 16:40
1

So my current approach is to create a separate package for lib.rs and use it as a dependency for the back-end, as outlined in here: What is an idiomatic way to have shared utility functions for integration tests and benchmarks? It seems to work well enough.

Gnut
  • 541
  • 1
  • 5
  • 19