...

/

Converting Rust into WebAssembly via wasm-bindgen

Converting Rust into WebAssembly via wasm-bindgen

Learn how to connect Rust WebAssembly and JavaScript using wasm-bindgen.

So far, we’ve seen simple examples. But how can we pass functions and classes from JavaScript into WebAssembly and vice versa? In order to do more advanced bindings, Rust provides us with wasm-bindgen. Let’s start with a “Hello World” example with wasm-bindgen.

Getting started with the project

  1. Create a new project with Cargo:

Press + to interact
cargo new --lib hello_world

This will create a new Rust project with all the necessary files.

  1. Open the Cargo.toml file to add crate-type and add the wasm-bindgen dependency:

Press + to interact
[package]
name = "hello_world"
version = "0.1.0"
authors = ["Educative"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2.38"

We define the wasm-bindgen dependency under the [dependencies] (line 9).

  1. Open the src/lib.rs file and replace the contents with the following:

Press + to interact
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn hello_world() -> String {
"Hello World".to_string()
}

We import the wasm_bindgen library using use wasm_bingen::prelude::* (line 1) and then annotate the function with #[wasm_bindgen] (line 2). The hello function returns String (line 4).

To generate the WebAssembly module, we’ll first run the following command:

Press + to interact
cargo build --target=wasm32-unknown-unknown

This will generate the WebAssembly module. But this module cannot run by itself. WebAssembly only supports passing numbers between the native code and JavaScript. But we’re ...