Skip to content

Instantly share code, notes, and snippets.

@toolness
Last active February 17, 2019 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toolness/a96621a0cb695f7da0cbc50ae7d97615 to your computer and use it in GitHub Desktop.
Save toolness/a96621a0cb695f7da0cbc50ae7d97615 to your computer and use it in GitHub Desktop.
A simple "hello world" using Rust wasm-bindgen that doesn't require webpack.

This is a simple proof-of-concept showing how to use Rust to generate WASM code without requiring the use of webpack.

For more context, see this Twitter thread.

I originally wrote this a while ago, but if I recall correctly, the key concept that allowed me to avoid the use of webpack was the --no-modules option to wasm-bindgen.

Instructions

You will need to rename lib.rs to src/lib.rs to get this to run (I had to flatten the directory structure to make it a gist).

Then run ./build.sh and open index.html in a browser using a static file server that serves WASM files with the proper MIME type (e.g. http-server).

You should see the text "Hello from wasm" in your console.

#! /bin/sh
cargo build --target=wasm32-unknown-unknown && \
wasm-bindgen --no-modules target/wasm32-unknown-unknown/debug/wasm_hello.wasm --out-dir .
[package]
name = "wasm_hello"
version = "0.1.0"
authors = ["Atul Varma <varmaa@gmail.com>"]
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
js-sys = "0.3.10"
wasm-bindgen = "0.2.33"
[dependencies.web-sys]
version = "0.3.4"
features = [
'console'
]
<!DOCTYPE html>
<meta charset="utf-8">
<title>Hi</title>
<p>Hi.</p>
<script src="wasm_hello.js"></script>
<script>
// I think this could actually just be `wasm_bindgen('./wasm_hello_bg.wasm')`,
// but that doesn't seem to work on some browsers, so I'll use this
// more traditional approach.
const response = fetch('./wasm_hello_bg.wasm')
.then(res => res.arrayBuffer())
.then(buf => WebAssembly.compile(buf))
.then(mod => wasm_bindgen(mod));
</script>
use wasm_bindgen::prelude::*;
use web_sys::console;
#[wasm_bindgen(start)]
pub fn start() -> Result<(), JsValue> {
console::log_1(&JsValue::from_str("Hello from wasm."));
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment