Next.js & React AVIF 2026:实施指南 [代码示例]
在Next.js和React中实施AVIF:自动转换、Image组件、优化。完整代码示例 →
Next.js Image Optimization
Next.js includes powerful built-in image optimization with AVIF support. The next/image component automatically serves AVIF to supporting browsers.
When you use the Image component from next/image, Next.js automatically converts images to WebP and AVIF formats on-demand. The server detects browser support via the Accept header and serves the optimal format.
This happens at the edge (with Vercel deployment) or on your server, with results cached for subsequent requests. Zero configuration needed for basic AVIF support.
next/image Configuration
Customize AVIF behavior through next.config.js.
// next.config.js
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
minimumCacheTTL: 60 * 60 * 24 * 30, // 30 days
dangerouslyAllowSVG: false,
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
}💡 专业提示
The formats array determines the order of format preference. Placing 'image/avif' first ensures it's served when supported.
Custom Image Loaders
For external image sources or CDNs, implement custom loaders with AVIF support.
Custom loaders work with any image CDN. The CDN handles format negotiation, typically through an 'f_auto' or similar parameter that detects browser AVIF support.
// Custom Cloudinary loader with AVIF
const cloudinaryLoader = ({ src, width, quality }) => {
const params = [
'f_auto', // Auto-detect AVIF/WebP support
'c_limit',
`w_${width}`,
`q_${quality || 'auto'}`
];
return `https://res.cloudinary.com/your-cloud/image/upload/${params.join(',')}/${src}`;
};
export default function ProductImage({ src, alt }) {
return (
<Image
loader={cloudinaryLoader}
src={src}
alt={alt}
width={800}
height={600}
quality={80}
/>
);
}Build-Time Processing
For static sites, process images at build time for maximum performance.
Build-time conversion is ideal for static content. All format conversion happens during build, eliminating runtime processing overhead. Sharp is the de facto library for Node.js image processing with excellent AVIF support.
// Using sharp for build-time AVIF conversion
import sharp from 'sharp';
import fs from 'fs';
import path from 'path';
async function convertToAvif(inputPath, outputPath) {
await sharp(inputPath)
.avif({ quality: 80 })
.toFile(outputPath);
}
// In getStaticProps or during build
export async function getStaticProps() {
const images = await processAllImages();
return { props: { images } };
}