Posted on Fri 10 July 2020

A simple way to run Rust WebAssembly in a browser

The 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 setup instructions to install the rust toolchain, wasm-pack and cargo-generate. You don't need npm.

Clone the example project template:

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 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:

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:

<!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 wasm-bindgen documentation for an explanation of the JavaScript code.

You can use Python to start a simple webserver:

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 開板. Theme by Giulio Fidente on github. .