Getting Started with WebAssembly
WebAssembly (WASM) is a binary format that allows high-performance execution in the browser. With WebAssembly, developers can run code written in multiple programming languages on the web efficiently.
This getting started guide will help you set up a simple project using WebAssembly and run an example using Rust.
1. Install Rust
First, install Rust by following the instructions at https://www.rust-lang.org/tools/install.
2. Add the `wasm32-unknown-unknown` target
Rust needs to be instructed to target WebAssembly. Open your terminal and run:
rustup target add wasm32-unknown-unknown
3. Install `wasm-pack`
`wasm-pack` is a helper tool that makes creating and publishing WebAssembly modules easier. Install it with:
npm install @wasm-tool/wasm-pack
4. Create a New Rust Project
Create a folder for your WebAssembly project and generate a new Rust package in it:
cd wasm-projects
cargo new hello-wasm
cd hello-wasm
5. Modify `Cargo.toml`
Edit `Cargo.toml` to add the wasm32 target and the `wasm-bindgen` dependency:
[package]
name = "hello-wasm"
version = "0.1.0"
edition = "2021"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
6. Write Some Code
Replace the contents of `src/lib.rs` with this example implementation:
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
pub fn hello(name: &str) -> String {
format!("Hello, {}! Welcome to WebAssembly.", name)
}
7. Build the Project
Use `wasm-pack` to build your project for the browser:
wasm-pack build --target web
This will create a `pkg` directory containing `.wasm` and JavaScript wrapper files.
8. Integrate with HTML
Create a new `index.html` file in the same folder as `pkg` and insert the following:
<html>
<head>
<title>Hello WebAssembly</title>
</head>
<body>
<h1>WebAssembly Example</h1>
<script type="module">
import init, { hello } from './pkg/hello_wasm.js';
async function run() {
await init();
document.body.innerText = hello('WebAssembly');
}
run();
</script>
</body>
</html>
9. Run the Project
Serve the files using a local development server like `http-server`, `vite`, or `live-server`. Open the HTML file in your browser to see the output.
10. Expand the Project
- Explore advanced features like DOM manipulation from Rust
- Experiment with other languages: C, C++, or Rust
- Connect WebAssembly with JavaScript for complex applications
- Optimize performance with WebAssembly and Rust
- Build cross-platform WebAssembly projects