Trunk WASM Web Application Bundler

repository·main·Indexed 26 days ago

https://github.com/trunk-rs/trunk

Trunk is a WASM web application bundler for Rust that simplifies building, bundling, and shipping Rust WASM applications to the web via a source HTML file. It includes a development server with support for HTTP and WebSocket proxies, automatic change detection for browser reloads, and the ability to bundle JavaScript snippets, images, CSS, and SCSS. Version 0.22.0-beta.2 supports various frameworks including Yew, Leptos, and Seed, as well as vanilla web-sys applications.

Tokens
15.2K
Snippets
47
Records
112
Agent score
87%

What's inside trunk

  1. Overview of Trunk WASM Bundler

    main

    Trunk is a WASM web application bundler for Rust. It uses a source HTML file to build and bundle WASM, JavaScript snippets, and other assets such as images, CSS, and SCSS.

    Key features include:

    • Dev server: A built-in server for rapid development, supporting HTTP and WebSocket proxies.
    • Change detection: Automatic watching of application changes to trigger builds and browser reloads.
  2. Create new self-signed certificates for local TLS

    main

    For local development scenarios, you can generate self-signed certificates using OpenSSL. Use the following command to create a key and certificate pair.

    CAUTION

    Using self-signed certificates is suitable for local development only. Using them in any other scenario may be dangerous.

    openssl req -new -newkey rsa:4096 -days 3650 -nodes -x509 \
        -subj "/C=XX/CN=localhost" \
        -keyout self_signed_certs/key.pem  -out self_signed_certs/cert.pem
  3. Run the Initializer example application

    main

    To run this example application, which demonstrates building a WASM application with custom initialization logic using web-sys, navigate to the example's directory and use the Trunk CLI to serve the application and open it in your browser.

    trunk serve --open
  4. Run Trunk behind a reverse proxy

    main

    To test how your application behaves when served behind a reverse proxy (like NGINX), you can use the --public-url and --serve-base flags. This configuration allows Trunk to serve the application at a specific sub-path relative to the proxy's root.

    Note: This setup is intended for testing purposes only. trunk serve is not designed to be a production application host. This is distinct from Trunk's built-in proxy feature.

  5. Configure Sub-resource integrity (SRI) for assets

    main

    Trunk can automatically generate hashes for assets and add the integrity attribute to the HTML tags of resources fetched by your web application. This feature is enabled by default using sha384 hashing.

    You can override the default behavior for specific assets by using the data-integrity attribute in your HTML/template. This allows you to either disable integrity checks or change the hashing algorithm used.

  6. Declare Link Assets in Trunk

    main

    To have Trunk process assets via <link> tags, you must follow these three rules:

    1. Use a valid HTML <link> tag.
    2. Add the data-trunk attribute.
    3. Set the rel attribute to one of the supported asset types (e.g., rust, sass, css, tailwind-css, icon, inline, copy-file, or copy-dir).

    Example: <link data-trunk rel="{type}" href="{path}" />

    Trunk will replace these elements with the processed output HTML.

  7. Copy files and directories to the dist directory

    main
    You can include images or other resource files in your dist directory by adding a <link> element to your source HTML. Trunk will copy the target resource to the dist directory unmodified (no hashing is applied) and remove the <link> tag from the final HTML output. This allows your WASM application to reference these assets via their relative paths.
  8. Configure Trunk using configuration files

    main

    Trunk uses a layered configuration system: Defaults < Configuration File < Command Line Arguments/Environment Variables.

    Trunk searches for configuration files in the local directory in the following order:

    • Trunk.toml
    • .trunk.toml
    • Trunk.yaml
    • .trunk.yaml
    • Trunk.json
    • .trunk.json

    If no file is found, Trunk uses metadata from Cargo.toml under the [package.metadata.trunk] section. You can also specify a specific file or directory using the --config CLI flag.

  9. Create a basic Rust web project with Trunk

    main

    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