Is there a way to build example as a library (WASM)?

I am making a library that I wanna use in WASM libraries which are also kinda libraries.

As a result, I wanna do something like this cargo build --example hello_world and get the hello_world.wasm as a result. In this case, there will be no main function in the code and I will get the message "main" function not found in crate "hello_world".

I could add empty fn main() {} and it would compile, but in that case, generated hello_world.wasm file will be way bigger than the one I would compile manually.

Is there a proper way to implement this type of scenario?


To load your code into WebAssembly you'll need to do two things:

  • Create a library (i.e. use instead of
  • Tell cargo to compile to WebAssembly by using cargo build --target wasm32-unknown-unknown (requires adding support for the WebAssembly target using rustup target add wasm32-unknown-unknown)

You may also want to check out the Rust and WebAssembly book. They've got a tutorial on implementing the game of life using a HTML canvas which does a pretty good job of showing you how to build things and then interact with JavaScript.

@Michael-F-Bryan thanks, I probably explained incorrectly. I do not have a problem building WASM library on its own. I wanna be able to compile multiple examples into relevant *.WASM but since wasm is not an executable cargo build --example [] --target wasm32-unknown-unknown does not work since [] is not an executable and does not have fn main in it.

I found the answer in cargo book. You can configure examples the same ways as binaries like so:

name = "hello-world"
crate-type = ["cdylib"]

This would build the hello-world into hello-world.wasm

1 Like

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.