Converting Rust into WebAssembly via wasm-bindgen
Learn how to connect Rust WebAssembly and JavaScript using wasm-bindgen.
We'll cover the following...
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
Create a new project with Cargo:
cargo new --lib hello_world
This will create a new Rust project with all the necessary files.
Open the
Cargo.toml
file to addcrate-type
and add thewasm-bindgen
dependency:
[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).
Open the
src/lib.rs
file and replace the contents with the following:
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:
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 ...