Duolith docs

Rust modules

When a page needs code that should be fast or shared with a server, such as parsing, maths or a codec, write it in Rust as a module, and call it from a page's script with its types. examples/rust-module is a whole example (decision 0078).

The shape

A module is a crate in the project's modules/<name>/, its own workspace:

my-app/
  modules/maths/
    Cargo.toml
    src/lib.rs
  pages/index.duo
# modules/maths/Cargo.toml
[package]
name = "maths"
version = "0.1.0"
edition = "2024"

[lib]
crate-type = ["cdylib", "staticlib", "rlib"]

[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "=0.2.130"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
uniffi = { version = "=0.29.4", optional = true }

[features]
native = ["dep:uniffi"]

[workspace]

Each exported function carries two attributes, one for the web and one for the phones:

#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::wasm_bindgen;

#[cfg(feature = "native")]
uniffi::setup_scaffolding!();

#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[cfg_attr(feature = "native", uniffi::export)]
pub fn slugify(text: &str) -> String {
    // ...
}

Calling it

A page imports the module by its folder, with one ../ for each folder between the file and the project root:

import { fibonacci, slugify } from "../modules/maths";

let n = state(10);
let answer = derived(() => fibonacci(n));

The build writes modules/maths/index.d.ts from the module's functions, so the editor and the type check know them: fibonacci("ten") is an error. The calls are synchronous; the WebAssembly is loaded before the page's script runs.

Building

duolith build compiles each module to WebAssembly (cargo build --release --target wasm32-unknown-unknown, then wasm-bindgen --target web) into _duolith/modules/<name>/. It needs, once:

rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version 0.2.130

The first build compiles the module's dependencies; later ones are incremental, in .duolith/target/.

CodeMeans
E0300Rust, the wasm32 target or wasm-bindgen is missing
E0301The crate does not compile; the compiler's message follows
E0303../modules/<name> names no folder
E0304The import's ../ steps do not lead to the project's modules/

duolith build --report lists each module on rung 3 of the execution ladder, with its size and the files that use it. The content security policy allows WebAssembly ('wasm-unsafe-eval') only when the build has a module, with nothing to configure.

On iOS and Android

UniFFI generates the Swift and Kotlin bindings:

pnpm --filter @duolith/modules bindings:native modules/maths

That writes .duolith/bindings/maths/{swift,kotlin} on any machine. Compiling the crate for a phone needs Xcode or the Android NDK, and the native build does not link modules yet: a native build of an app with a module is refused with E0211. native/DEVICE-CHECKLIST.md lists the device steps.