Converting Rust into WebAssembly via wasm-bindgen
Let's start with a Hello World example with wasm-bindgen
:
- Create a new project with Cargo:
$ cargo new --lib hello_world Created library `hello_world` package
This will create a new Rust project with all the necessary files.
- Open the project in your favorite editor. Open the
Cargo.toml
file to addcrate-type
and add thewasm-bindgen
dependency:[package] name = "hello_world" version = "0.1.0" authors = ["Sendil Kumar"] edition = "2018" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2.38"
- We define the dependency under the
[dependencies]
table in thetoml
file. Open thesrc/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::*
and then...