A really small rust + wasm example using webpack. Current packaged size is 29.8 KB uncompressed.
git clone this repo then make run
Navigate to http://[::]:8000/ or http://127.0.0.1:8000
makefor handling builds.rust(i.ecargo) andwasm-packfor building.- (optional)
python3simple.httpused formake runandmake release-test
make build will build wasm file + js shim to dist/.
make release will clean, build with release flags and then copy required files to www/, which can then be hosted with your http server of choice. Release builds can be significantly smaller then dev builds.
make run builds and hosts a basic web server with python3 from the current directory.
release-test performs a release build and hosts a basic web server with python3 from the www/ directory.
Suggest reading the wasm-bindgen book for more information.
use wasm_bindgen::prelude::*;// Async boilerplate - marks this function (main()) as the entrypoint to the browser.#[wasm_bindgen(start)]pubfnmain() -> Result<(),JsValue>{// Lots of expects - each of these could cause an error if the required item doesn't exist (or can't be created)let window = web_sys::window().expect("no global `window` exists");let document = window.document().expect("should have a document on window");let body = document.body().expect("document should have a body");// Creates a new p element: <p>"Hello, world!"</p>let p = document.create_element("p")?;
p.set_inner_html("Hello, world!");// Try to add our <p> element to the document body
body.append_child(&p).unwrap();// End of Async code - not that javascript cares :DOk(())}// Function should exported to javascript. Note standard javascript typings used.#[wasm_bindgen]pubfnadd(a:u32,b:u32) -> u32{
a + b
}...
<scripttype="module">importinit,{add}from'./dist/index.js';asyncfunctionrun(){awaitinit();console.log(add(2,1));}run();</script>
...#[wasm_bindgen]extern{#[wasm_bindgen(js_namespace = console)]fnlog(s:&str);}log("Hello, console!");