图片优化
规则
- 在 Next.js 中对所有图片使用
next/image — 自动优化、懒加载、响应式 srcset
- 始终设置
width 和 height,或使用 fill 配合固定容器 — 防止布局偏移 (CLS)
- 模糊占位图:在构建/上传时使用
plaiceholder 生成 blurDataURL,或对静态导入使用 placeholder="blur"
- 远程图片:在
next.config.js 中配置 remotePatterns — 白名单 CDN 域名
- 上传流程:客户端 → 预签名 URL (S3/R2/Supabase Storage) → 直接上传 → 将 URL 存入数据库
- 上传时调整大小:使用
sharp 在服务端创建多种尺寸(缩略图、中等、全尺寸)— 不要提供原始图片
- 格式:通过
next/image 自动格式提供 WebP/AVIF — 降级为 JPEG 以保证兼容性
- CDN 分发:将原始图片存储在对象存储中 (S3, R2),通过 CDN (CloudFront, Cloudflare) 提供服务,并设置缓存头
- 最大文件大小验证:在客户端(上传前)和服务器端(处理前)进行检查 — 典型限制为 5-10MB
模式
import Image from "next/image";
<Image
src="/hero.jpg"
alt="英雄图片"
width={1200}
height={630}
placeholder="blur"
blurDataURL="data:image/jpeg;base64,/9j/4AAQ..."
priority // 首屏
/>
<div className="relative aspect-video">
<Image src={url} alt={alt} fill className="object-cover" sizes="(max-width: 768px) 100vw, 50vw" />
</div>
import sharp from "sharp";
async function processUpload(buffer: Buffer) {
const thumbnail = await sharp(buffer).resize(200, 200, { fit: "cover" }).webp({ quality: 80 }).toBuffer();
const medium = await sharp(buffer).resize(800).webp({ quality: 85 }).toBuffer();
const full = await sharp(buffer).resize(1920).webp({ quality: 90 }).toBuffer();
return { thumbnail, medium, full };
}
避免
- 在 Next.js 中使用
<img> 标签 — 会失去自动优化、懒加载和格式转换
- 响应式图片缺少
sizes 属性 — 浏览器无法选择合适的 srcset 尺寸
- 提供未调整大小的原始图片 — 将 5MB 的照片显示为 400px 是浪费
- 跳过文件类型验证 — 在服务端检查 MIME 类型,而不仅仅是文件扩展名