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.
.webp
format for optimal size and quality.priority
prop. The component adds a preload <link>
to the document head, improving load times and enhancing your site's performance.Add leptos_image via cargo:
bash
cargo add leptos_image
Add the SSR Feature under [features]
in your Cargo.toml
toml
[features]
ssr = [
"leptos_image/ssr",
# ...
]
REQUIRES SSR + AXUM
Go to your SSR Main Function in main.rs
Before you create your router, call the cache_app_images
function with the project root. This will cache all the images in your app, and generate the LQIPs.
If you have a lot of images, then you should probably only call this function in production because it will delay your server startup.
If you don't include this function, then image caching will happen at runtime.
```rust
use leptos::; use leptos_image::;
let conf = getconfiguration(None).await.unwrap(); let leptosoptions = conf.leptosoptions; let root = leptosoptions.site_root.clone();
use leptosimage::cache::cacheapp_images;
cacheappimages(root, |cx: Scope| view! {cx,
```
Next add an endpoint to your router that serves the cached images. For now, the endpoint path must be /cache/image
and is not configurable
```rust
use axum::{routing::{get, post}, Router};
let router = ...
router.route("/cache/image", get(imagecachehandler));
```
Next inside of leptos_routes, call the provide_image_context
function. This will provide the Image Context to your App during SSR.
The final router should look something like this!
```rust
let router = Router::new()
.route("/api/*fnname", post(leptosaxum::handleserverfns))
.leptosroutes(&leptosoptions, routes, |cx| {
// Image Context is provided here!
provideimagecontext(cx);
view! { cx,
```
Now you can use the Image Component anywhere in your app!
```rust
pub fn MyPage(cx: Scope) -> impl IntoView { view! { cx,
And that's it. You're all set to use the Image Component.
api/post/:id
in Route path).