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 |
|
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 |
|
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 |
|
See the [cached]wasm-bindgen documentation for an explanation of the JavaScript code.
You can use Python to start a simple webserver:
1 |
|
then run your first WebAssembly script in your browser: http://localhost:8080/.
Tags: programming, rust, web, wasm, js