Posted on Fri 10 July 2020

A simple way to run Rust WebAssembly in a browser

The [cached]Rust WebAssemply book has a detailed introduction to WebAssembly in Rust; unfortunately it's example setup is somewhat complicated and requires the use of npm just to run show a simple Hello World! message in the browser.

Luckily, there's a simpler way to get started if you don't care about npm modules.

First, follow the [cached]setup instructions to install the rust toolchain, wasm-pack and cargo-generate. You don't need npm.

Clone the example project template:

1
cargo generate --git https://github.com/rustwasm/wasm-pack-template

which will prompt you for a project name, in the following we'll assume you used browser-wasm.

See the [cached]book for a detailed description of all the files this template generates; for our purposes you can build the rust library and generate a wasm file by running:

1
wasm-pack build -t web

Note the -t web: this differs from the book, it will generate JavaScript code that you can directly load in your browser without any need for npm packaging. Ideal if you just want to generate some wasm that you can inline in your blog!

The generated code will be in a pkg subdirectory of your project. To test it, create a index.html file in your project directory with the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Hello wasm-pack!</title>
</head>

<body>
    <script type="module">
        // The filename has to match your project name.
        import init, { greet } from './pkg/browser_wasm.js';

        async function main() {
            await init();
            greet();
        }

        main();
    </script>
</body>

</html>

See the [cached]wasm-bindgen documentation for an explanation of the JavaScript code.

You can use Python to start a simple webserver:

1
python -m SimpleHTTPServer 8080

then run your first WebAssembly script in your browser: http://localhost:8080/.

Tags: programming, rust, web, wasm, js

© Julian Schrittwieser. Built using Pelican. Theme by Giulio Fidente on github. .