You call Rust from JavaScript by compiling your Rust code to a WebAssembly (.wasm) binary and loading it into the browser using the wasm-bindgen toolchain.
# 1. Add dependencies to Cargo.toml
[dependencies]
wasm-bindgen = "0.2"
[lib]
crate-type = ["cdylib"]
# 2. Write Rust code with #[wasm_bindgen] macro
// src/lib.rs
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
# 3. Build for the web target
cargo install wasm-bindgen-cli
cargo build --target wasm32-unknown-unknown --release
wasm-bindgen target/wasm32-unknown-unknown/release/your_crate.wasm --out-dir pkg
# 4. Import in JavaScript
// index.js
import init, { add } from './pkg/your_crate.js';
init().then(() => {
console.log(add(1, 2)); // Outputs: 3
});