Leptos <Image/> (Batteries included)

Crafted with inspiration from Next.js

Images make a substantial impact on the size and performance of a website, so why not get them right?

Enter Leptos <Image/>, a component that enhances the standard HTML <img> element with automatic image optimization features.

Quick Start

REQUIRES SSR + AXUM

Add leptos_image via cargo:

cargo add leptos_image

In the base of your App, wrap everything (including Router) in <ImageProvider/>

```rust // In your main App. use leptos::; use leptos_meta::; use leptos_image::{Image, ImageProvider};

[component]

pub fn App(cx: Scope) -> impl IntoView { providemetacontext(cx);

view! { cx,
    <Title text="Welcome to Leptos"/>
    // Wrap the base of your App with ImageProvider
    <ImageProvider>
        <MyPage/>
        // The rest of your App...
    </ImageProvider>
}

}

// Now you can use the Image Component anywhere in your app!

[component]

pub fn MyPage(cx: Scope) -> impl IntoView { view! { cx, <Image src="/cute_ferris.png" blur=true width=750 height=500 quality=85 /> } }</p> <p>```</p> <p>Next go to your SSR Main Function in <code>main.rs</code></p> <p>Before you create your router, call the <code>cache_app_images</code> function with the project root. This will cache all the images in your app, and generate the LQIPs</p> <p>```rust</p> <p>use leptos::*;</p> <p>let conf = get<em>configuration(None).await.unwrap(); let leptos</em>options = conf.leptos<em>options; let root = leptos</em>options.site_root.clone();</p> <p>use leptos<em>image::cache::cache</em>app_images;</p> <p>cache<em>app</em>images(root, |cx: Scope| view! {cx, <App/>}) .await .expect("Failed to cache images");</p> <p>```</p> <p>Next add an endpoint to your router that serves the cached images. For now, the endpoint path must be <code>/cache/image</code> and is not configurable</p> <p>```rust</p> <p>use axum::{routing::{get, post}, Router}; use leptos<em>image::handlers::image</em>cache_handler;</p> <p>let router = ...</p> <p>router.route("/cache/image", get(image<em>cache</em>handler));</p> <p>```</p> <p>The final router should look something like this!</p> <p>```rust</p> <p>let router = Router::new() .route("/api/*fn<em>name", post(leptos</em>axum::handle<em>server</em>fns)) .leptos<em>routes(&leptos</em>options, routes, |cx| { view! { cx, <App/> } }) // Here's the new route!. .route("/cache/image", get(image<em>cache</em>handler)) .with<em>state(leptos</em>options);</p> <p>```</p> <p>And that's it. You're all set to use the Image Component.</p> <h2>Caveats:</h2> <ul> <li>Images will only be retrieved from routes that are non-dynamic (meaning not <code>api/post/:id</code> in Route path).</li> <li>Images can take a few seconds to optimize, meaning first startup of server will be slower.</li> <li>Actix Support is coming soon!</li> </ul> </body></html>