MDX Image Optimization with astro:assets
MDX Image Optimization with astro:assets
Section titled “MDX Image Optimization with astro:assets”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
Section titled “The Image Component”The Image component from astro:assets provides:
- Format conversion: Automatic WebP, AVIF, JPEG, PNG conversion
- Responsive images: Auto-generated
srcsetattributes - Lazy loading: Native
loading="lazy"support - Aspect ratio preservation: Prevents CLS (Cumulative Layout Shift)
Basic Usage
Section titled “Basic Usage”---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" />getImage() Function
Section titled “getImage() Function”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",});Image Properties
Section titled “Image Properties”The optimizedImage object contains:
src: The optimized image URLsrcset: Thesrcsetattribute for responsive imageswidth: The image widthheight: The image heightformat: The image format (webp, avif, jpeg, png)
Using in MDX
Section titled “Using in MDX”---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" />Benefits
Section titled “Benefits”- Smaller File Sizes: WebP is 25-35% smaller than PNG/JPEG, AVIF is 50% smaller
- Faster Loading: Optimized images load faster, improving LCP
- Responsive:
srcsetensures optimal image size for each device - No CLS: Preserved aspect ratios prevent layout shifts
Verification
Section titled “Verification”After building, check the dist/ directory for:
- WebP and AVIF versions of images
srcsetattributes in generated HTML- Optimized image files