To start a web application with Trunk, you need a standard Cargo project and an index.html file acting as the entry point. Trunk uses cargo build and wasm-bindgen under the hood to compile your Rust code to WebAssembly and serve it.
1. Initialize the project
Create a new Cargo project and navigate into it:
cargo new trunk-hello-world
cd trunk-hello-world
2. Add web dependencies
Add wasm-bindgen for JS interop, console_error_panic_hook for better error reporting in the browser, and web_sys with the necessary features to access browser APIs:
cargo add wasm-bindgen console_error_panic_hook
cargo add web_sys -F Window,Document,HtmlElement,Text
3. Implement the application logic
Create src/main.rs with your Rust code. A basic example that manipulates the DOM looks like this:
use web_sys::window;
fn main() {
console_error_panic_hook::set_once();
let document = window()
.and_then(|win| win.document())
.expect("Could not access the document");
let body = document.body().expect("Could not access document.body");
let text_node = document.create_text_node("Hello, world from Vanilla Rust!");
body.append_child(text_node.as_ref())
.expect("Failed to append text");
}
4. Create the entry point
Create an index.html file in the root of your project. Trunk will use this file as a template to inject the WASM loader:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Hello World</title>
</head>
<body>
</body>
</html>
5. Build and serve
Run the following command to compile the project and start a local development server:
trunk serve --open
This command compiles the project, runs wasm-bindgen, and opens your default browser to the served application.
# Setup steps
cargo new trunk-hello-world
cd trunk-hello-world
# Dependencies
cargo add wasm-bindgen console_error_panic_hook
cargo add web_sys -F Window,Document,HtmlElement,Text
# Run development server
trunk serve --open