In-browser WebAssembly we trust
Rust compiles to machine code, which runs as an executable file on your computer. You can also compile it to WebAssembly (Wasm for short) and have it run in the browser.
Until recently, if you wanted to add interactivity to a web page, or do a bunch of calculations in-browser, you'd use JavaScript. Now that Wasm is supported in all modern browsers, we can use Rust (or another compatible language) and run much closer to the metal.
Good times! Here's how to do it.
Firstly, install wasm-pack. It's a tool that helps build Rust code for the web.
Then, create a new Rust project with wasm-pack new my-wasm-project
. This will generate a basic Rust library for you.
We only need to worry about src/lib.rs
for now.
use *;
extern "C"
The extern "C"
block pulls the alert
function in from JavaScript and we "export" the greet
function using pub
so we can call it from JavaScript.
Those #[wasm_bindgen]
annotations are what bind our Rust code to JavaScript. They tell the compiler where the Wasm module should interface with JavaScript.
The alert
function ... shows an alert box on the page. Cool. Let's do something a bit more interesting!
use *;
This function calculates the nth Fibonacci number. Now we can hook it up and call this function from our page. But first, we need to compile it into WebAssembly.
Build your Wasm module with wasm-pack build --target web
in the root of your project. This will create a pkg
directory with a wasm.js
file and a wasm_bg.wasm
file.
We'll need an index.js
file at the root of our project to import our Wasm module.
;
await ;
;
result; // 2178309
And an index.html
to load our script.
Hello World!
Hello World!
Now serve your root directory with miniserve (or your favourite local static file server) and open index.html
in your browser. You should see the result of the fibonacci
function in the console.
The 32nd Fibonacci number is 2178309 btw.
And there you have it. Wasm running in-browser.
'Till next time. ✌️