Integrating WebAssembly with JavaScript
Introduction
WebAssembly (often abbreviated as wasm) is a binary instruction format for a stack-based virtual machine. It allows developers to run code written in multiple languages on the web at near-native speed. In this tutorial, we'll explore how to integrate WebAssembly with JavaScript using Rust, a systems programming language that offers high performance and safety.
Prerequisites
Before we begin, ensure you have the following installed on your machine:
- Rust: You can install Rust by following the instructions at rust-lang.org.
- Wasm Pack: This tool helps build Rust-generated WebAssembly packages. Install it via:
- A modern web browser: Ensure you are using a browser that supports WebAssembly (e.g., Chrome, Firefox, Safari).
cargo install wasm-pack
Building a Simple WebAssembly Module
Let's create a simple Rust function that we will compile to WebAssembly. This function will take two numbers and return their sum.
Follow these steps:
- Create a new Rust library project:
- Change to the project directory:
- Update your
Cargo.toml
file to include thewasm-bindgen
dependency: - Add the following Rust code in
src/lib.rs
:
cargo new --lib wasm_sum
cd wasm_sum
[dependencies] wasm-bindgen = "0.2.78"
use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn add(a: i32, b: i32) -> i32 { a + b }
Compiling to WebAssembly
Now that we have our Rust function, let's compile it to WebAssembly using Wasm Pack. Run the following command in your project directory:
wasm-pack build --target web
This command will generate a pkg
directory containing the compiled WebAssembly binary and the necessary JavaScript bindings to interact with it.
Creating the HTML and JavaScript Interface
Next, we will create an HTML file that loads our WebAssembly module and allows users to add two numbers. Create an index.html
file in the root of your project with the following content:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>WASM Sum</title> <script src="pkg/wasm_sum.js"></script> <script> async function run() { const { add } = await import('./pkg/wasm_sum.js'); document.getElementById('addButton').onclick = () => { const a = parseInt(document.getElementById('num1').value); const b = parseInt(document.getElementById('num2').value); const result = add(a, b); document.getElementById('result').textContent = 'Result: ' + result; }; } run(); </script> </head> <body> <h1>WASM Sum Example</h1> <input id="num1" type="number" placeholder="Enter first number"> <input id="num2" type="number" placeholder="Enter second number"> <button id="addButton">Add</button> <p id="result">Result: </p> </body> </html>
Running the Application
To view your application, you can use a simple HTTP server. You can use python
for this purpose. Run the following command in your project directory:
python -m http.server 8000
Open your browser and navigate to http://localhost:8000
. You should see the input fields and a button. Enter two numbers and click "Add" to see the result calculated using WebAssembly.
Conclusion
In this tutorial, we successfully integrated WebAssembly with JavaScript using Rust. We created a simple function, compiled it to WebAssembly, and built a web interface to interact with it. This integration allows developers to harness the performance benefits of WebAssembly while using the flexibility of JavaScript for web applications.