DEV Community

Cover image for How to create Web Apps in pure Rust
Andreas Tzionis
Andreas Tzionis

Posted on

How to create Web Apps in pure Rust

TinyWeb enables client-side applications to be built in pure Rust, similar to backend applications, leveraging the language strict type system and great built-in tooling.

It has a tiny footprint with less than 800 lines of code, has no build step and no external dependencies. Yet, it support full-featured webapps!

Option 1. Use the starter project

git clone https://github.com/LiveDuo/tinyweb-starter
Enter fullscreen mode Exit fullscreen mode

Option 2. Create a new project

1. Create a Rust project

Create a new Rust project with cargo new tinyweb-example --lib. Add crate-type =["cdylib"] in Cargo.toml and install the crate with cargo add tinyweb --git https://github.com/LiveDuo/tinyweb.

2. Add sample code

Update the src/lib.rs:

use tinyweb::element::El;
use tinyweb::invoke::Js;

fn component() -> El {
    El::new("div")
        .child(El::new("button").text("print").on("click", move |_| {
            Js::invoke("alert('hello browser')", &[]);
        }))
}

#[no_mangle]
pub fn main() {
    let body = Js::invoke("return document.querySelector('body')", &[]).to_ref().unwrap();
    component().mount(&body);
}
Enter fullscreen mode Exit fullscreen mode

3. Load wasm in HTML

Create an index.html in a new public folder:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://cdn.jsdelivr.net/gh/LiveDuo/tinyweb/src/js/main.js"></script>
        <script type="application/wasm" src="client.wasm"></script>
    </head>
    <body></body>
</html>
Enter fullscreen mode Exit fullscreen mode

4. Build the wasm

Build the project with cargo build --target wasm32-unknown-unknown -r. Then cp target/wasm32-unknown-unknown/release/*.wasm public/client.wasm to get the .wasm in the right place and serve the public folder with any static http server.

Top comments (0)