How to Use Rust WASM in a React/Vue/Svelte Application

Web
Build Rust code to WebAssembly using wasm-pack and import the generated module into your React, Vue, or Svelte application.

Use wasm-pack to build your Rust library into a WebAssembly module, then import it directly into your React, Vue, or Svelte component.

wasm-pack build --target web
cargo install wasm-pack
  1. Initialize a new Rust library project with cargo new --lib my-wasm-lib.
  2. Add the wasm-bindgen and js-sys dependencies to your Cargo.toml.
  3. Write your Rust code and export functions using the #[wasm_bindgen] attribute.
  4. Run wasm-pack build --target web in the library directory to generate the .wasm file and JavaScript bindings.
  5. Copy the generated pkg folder contents into your frontend project's public or src directory.
  6. Import the generated JavaScript module in your React, Vue, or Svelte component and call the exported functions.