Setup WebAssembly with Rust
Yesterday, I gave an overview of the topic that I would like to write about as a continuation.
With this small post I want to show how easy it is to setup a WebAssembly project with Rust, as it is one of the most favorite alternatives to AssemblyScript.
Requirements
For all of this we first need the Rust compiler with Cargo package manager.
WASM Compiler
With wasm-pack exists a compiler, which build .wasm
files from Rust code and additionally create the corresponding JavaScript modules + TypeScript declaration files.
To install the application, run
cargo install wasm-pack
in your terminal.
Execution of
wasm-pack --version
will display the installed version and indirectly check if CLI tool works correctly.
Create the Rust project
For my demo project, I run
cargo new --lib wasm-in-rust
to create a new library project.
I replaced the initial example file with content of src/lib.rs:
use wasm_bindgen::prelude::*;
/// Squares a number.
///
/// # Arguments
///
/// * `val` - The input value.
#[wasm_bindgen]
pub fn pow2(val: i32) -> i32 {
val * val // simple return
}
Before this worked, I had to update the Cargo.toml file, with information about the library type (cdylib) and the module I need (wasm-bindgen):
[package]
name = "wasm-in-rust"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.92"
Build and run the project
Final .wasm
files can be created for 2 different main targets:
On the one hand for websites, for which you executes the command
wasm-pack build --target web
in your terminal and on the other hand for Node.js environments by executing
wasm-pack build --target nodejs
To simplify this, I added two NPM scripts in package.json file:
npm run start
: executes the code of index.tsnpm run start:web
: starts a new webserver athttp://localhost:3000/
, which provides the content of index.html, that itself includes the WASM module from wasm.js
Both scripts do a build before anything is started and executed.
Conclusion
Rust can often be the better solution for implementing more complex WebAssembly modules than AssemblyScript.
Fortunately, setting up projects through existing tools and compilers is also very easy.
Have fun while trying it out! 🎉