How to Use wasm-bindgen for Rust-JavaScript Interop

Web
Use wasm-bindgen to compile Rust to WebAssembly and automatically generate JavaScript bindings for seamless interop.

Use the wasm-bindgen crate to generate glue code that allows JavaScript to call Rust functions and vice versa. Add the dependency, mark your functions with #[wasm_bindgen], compile to wasm32-unknown-unknown, and link the output in your HTML.

[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]

[profile.release]
lto = true
use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn greet(name: &str) -> String {
    format!("Hello, {}!", name)
}
  1. Compile the Rust library to WebAssembly using cargo build --target wasm32-unknown-unknown --release.
  2. Generate JavaScript bindings with wasm-bindgen target/wasm32-unknown-unknown/release/your_crate.wasm --out-dir pkg.
  3. Include the generated JavaScript file in your HTML page via a <script> tag.
  4. Import the Rust module in your JavaScript code using import init, { greet } from './pkg/your_crate.js';.
  5. Initialize the module by calling await init(); before invoking any exported functions.