Rust WebAssembly/wasm Hello World Example
These are my notes on how to get a wasm tool up and running. It's largely the same as the MDN tutorial but with way less cruft.
-
Install
wasm-pack. -
Create a new library rust project and
cdinto the directory. -
Add the
wasm-bindgencrate. -
Add this to the
Cargo.tomlfile.[lib] crate-type = ["cdylib"]The file should look something like this when you're done:
[package] name = "hello-world" version = "0.1.0" edition = "2024" [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2.108" -
Replace the contents of:
with:
use *; extern "C" -
Make sure you're still in the
hello-worlddirectory with theCargo.tomlfile in it and run this to build the package:That will create a new
pkgfolder with the wasm files. -
Create an
index.htmlfile in the same folder as theCargo.tomlfile with this content.hello-wasm example
With all that done, you can serve the directory with the index.html
file in it and everything should work as expected.
-a
Endnotes
Looking at this example that shows how to make a package without a bundler it sounds like you always need to do an async start-up of the module right now. That may change in the future.
The example isn't that useful. I haven't seen alert() used in forever.
This is code for another example that gives you a button to press. I need to polish it and move it to the main section. Just keeping it here until I get to that.
(this is for a crate named wasm_example instead of hello-world
use *;
0
Of interest is the fact that I didn't have to do before passing to the wasm module. It seems to have just converted the type in flight.