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)
}
- Compile the Rust library to WebAssembly using
cargo build --target wasm32-unknown-unknown --release. - Generate JavaScript bindings with
wasm-bindgen target/wasm32-unknown-unknown/release/your_crate.wasm --out-dir pkg. - Include the generated JavaScript file in your HTML page via a
<script>tag. - Import the Rust module in your JavaScript code using
import init, { greet } from './pkg/your_crate.js';. - Initialize the module by calling
await init();before invoking any exported functions.