web-sys: DOM hello world
Using web-sys we're able to interact with all the standard web platform methods, including those of the DOM! Here we take a look at a simple "Hello, world!" which manufactures a DOM element in Rust, customizes it, and then appends it to the page.
_ [wasm-bindgen Guide]
setup the project
cargo new dom --lib
cd dom
mkdir -p www/js www/html
cargo add wasm-bindgen
edit Cargo.toml to add crate-type
[lib]
crate-type = ["cdylib",]
in www/html/index.html
we have
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<title>DOM nobundle</title>
</head>
<body>
<script type="module" src="../js/index.js"></script>
</body>
</html>
and in www/js/index.js
import init from "../pkg/dom.js"
async function run() {
const wasm = await init();
}
run();
Everything happens in src
#![allow(unused)] fn main() { // src/lib.rs use wasm_bindgen::prelude::*; // Called by our JS entry point to run the example #[wasm_bindgen(start)] fn run() -> Result<(), JsValue> { // Use `web_sys`'s global `window` function to get a handle on the global // window object. 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"); // Manufacture the element we're gonna append let val = document.create_element("p")?; val.set_text_content(Some("Hello from Rust!")); body.append_child(&val)?; Ok(()) } }
Note:
We need to add web-sys as a dependency and make some features available in Cargo.toml
.
[dependencies]
wasm-bindgen = "0.2.88"
[dependencies.web-sys]
version = "0.3.65"
features = [
'Document',
'Element',
'HtmlElement',
'Node',
'Window',
]
build and serve
wasm-pack build --target web --no-typescript --out-dir www/pkg
http www
open index.html
firefox http://localhost:8000/html/
What's next?
<--
js-sys: WebAssembly in WebAssembly
web-sys: Closures -->