<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.
.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.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};
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!
pub fn MyPage(cx: Scope) -> impl IntoView { view! { cx,
```
Next 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::*;
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}; use leptosimage::handlers::imagecache_handler;
let router = ...
router.route("/cache/image", get(imagecachehandler));
```
The final router should look something like this!
```rust
let router = Router::new()
.route("/api/*fnname", post(leptosaxum::handleserverfns))
.leptosroutes(&leptosoptions, routes, |cx| {
view! { cx,
```
And that's it. You're all set to use the Image Component.
api/post/:id
in Route path).