Zum Inhalt springen

MDX Image Optimization with astro:assets

Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.

In Astro 7.x, image optimization is built into the core through the astro:assets module. When using MDX files, you can leverage the Image component and getImage() function for optimized images with WebP/AVIF formats and srcset attributes.

The Image component from astro:assets provides:

  • Format conversion: Automatic WebP, AVIF, JPEG, PNG conversion
  • Responsive images: Auto-generated srcset attributes
  • Lazy loading: Native loading="lazy" support
  • Aspect ratio preservation: Prevents CLS (Cumulative Layout Shift)
---
title: Image Optimization Example
---
import { Image, getImage } from 'astro:assets';
import myImage from '../../assets/images/my-image.png';
const optimizedImage = await getImage({
src: myImage,
width: 1200,
quality: 75,
formats: ['webp', 'avif', 'jpeg'],
});
<Image src={optimizedImage} alt="Optimized image" loading="lazy" />

The getImage() function returns an object with optimized image properties:

const optimizedImage = await getImage({
src: myImage,
width: 1200, // Target width
quality: 75, // Image quality (1-100)
formats: ['webp', 'avif', 'jpeg'], // Output formats
// Optional: sizes for responsive images
sizes: "100vw",
});

The optimizedImage object contains:

  • src: The optimized image URL
  • srcset: The srcset attribute for responsive images
  • width: The image width
  • height: The image height
  • format: The image format (webp, avif, jpeg, png)
---
title: Multiple Images
---
import { Image, getImage } from 'astro:assets';
import image1 from '../../assets/images/image1.png';
import image2 from '../../assets/images/image2.png';
const images = {
image1: await getImage({ src: image1, width: 1200, quality: 75, formats: ['webp', 'avif', 'jpeg'] }),
image2: await getImage({ src: image2, width: 1200, quality: 75, formats: ['webp', 'avif', 'jpeg'] }),
};
# My Page
<Image src={images.image1} alt="Image 1" loading="lazy" />
<Image src={images.image2} alt="Image 2" loading="lazy" />
  1. Smaller File Sizes: WebP is 25-35% smaller than PNG/JPEG, AVIF is 50% smaller
  2. Faster Loading: Optimized images load faster, improving LCP
  3. Responsive: srcset ensures optimal image size for each device
  4. No CLS: Preserved aspect ratios prevent layout shifts

After building, check the dist/ directory for:

  • WebP and AVIF versions of images
  • srcset attributes in generated HTML
  • Optimized image files