James Bachini

Creating WASM Files Using Rust and Running Them in the Browser

Web WASM Rust

In this tutorial we will be writing some code in Rust, compiling to web assembly (WASM) and then running that code in a browser. This enables high performance applications to be run within a web dev setting.

In this tutorial I’ll be using windows subsystem for Linux. Let’s first install Rust and wasm-pack (more instructions for how to install rust on different operating systems here)

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
cargo install wasm-pack

Now let’s set up a new directory and add the WebAssembly target

cargo new hello-wasm --lib
cd hello-wasm
rustup target add wasm32-unknown-unknown

We will then go into the directory and open up the Cargo.toml file and add the following dependency and library

[dependencies]
wasm-bindgen = "0.2"

[lib]
crate-type = ["cdylib"]

Now go in and edit src/lib.rs, replace the entire file with the code below

use wasm_bindgen::prelude::*;

#[wasm_bindgen]
pub fn loop(name: &str) -> String {
    format!("Hello, {}!", name)
}

Let’s build and pack it into a wasm file. This command compiles the Rust code to WASM and places the output in the pkg directory.

wasm-pack build --target web

Now let’s embed this code into a web page called index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple WASM Example</title>
</head>
<body>
    <h1>Simple Rust + WASM Example</h1>
    <input type="text" id="name-input" placeholder="Enter your name" />
    <button id="greet-btn">Greet</button>
    <h2 id="greeting"></h2>
    <script type="module">
        import init, { greet } from './pkg/hello_wasm.js';
        async function run() {
            await init();  // Initialize the WASM module
            const button = document.getElementById('greet-btn');
            const input = document.getElementById('name-input');
            const greeting = document.getElementById('greeting');
            button.addEventListener('click', () => {
                const name = input.value;
                greeting.textContent = greet(name);
            });
        }

        run();
    </script>
</body>
</html>

We can pop this onto a webserver with the wasm files in pkg/ and run it from a browser.

wasm rust web example

This is a basic example of how to get data from javascript in a web browser to a wasm module executing web assembly built from Rust code.


Get The Blockchain Sector Newsletter, binge the YouTube channel and connect with me on Twitter

The Blockchain Sector newsletter goes out a few times a month when there is breaking news or interesting developments to discuss. All the content I produce is free, if you’d like to help please share this content on social media.

Thank you.

James Bachini

Disclaimer: Not a financial advisor, not financial advice. The content I create is to document my journey and for educational and entertainment purposes only. It is not under any circumstances investment advice. I am not an investment or trading professional and am learning myself while still making plenty of mistakes along the way. Any code published is experimental and not production ready to be used for financial transactions. Do your own research and do not play with funds you do not want to lose.


Posted

in

, , ,

by