图片优化
next/image 是 Next.js 官方的 <img> 替代品,自动完成:
- 尺寸优化:按设备分发合适尺寸 + WebP。
- 视觉稳定:自动防止加载时的布局抖动(CLS)。
- 更快首屏:懒加载 + 可选 blur 占位图。
- 资源灵活:本地或远程图片都能按需缩放。
基本用法
import Image from 'next/image';
export default function Page() {
return <Image src="/profile.png" alt="头像" width={500} height={500} />;
}
src 可以是本地路径或远程 URL。
本地图片
把静态资源放在根目录的 public/ 下,直接用 /xxx.png 引用。
推荐方式:静态 import,这样 width、height、blurDataURL 都会自动填上:
import Image from 'next/image';
import ProfileImage from './profile.png';
export default function Page() {
return (
<Image
src={ProfileImage}
alt="头像"
// width / height / blurDataURL 自动提供
placeholder="blur"
/>
);
}
文件名不定?用动态 import
博客封面之类路径来自数据的场景,可以在服务端组件里用 import():
import Image from 'next/image';
async function PostImage({ imageFilename, alt }: { imageFilename: string; alt: string }) {
const { default: image } = await import(`../content/blog/images/${imageFilename}`);
return <Image src={image} alt={alt} />;
}
路径里必须带一个 静态前缀(../content/blog/images/),Next.js 会把这个目录下所有文件打进产物,外部无法跳出该目录。
远程图片
远程 URL 要自己提供 width / height(或用 fill),因为构建期 Next.js 并不能访问远端图:
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="头像"
width={500}
height={500}
/>
同时需要在 next.config.ts 白名单中允许该域名,防止 URL 被滥用:
import type { NextConfig } from 'next';
const config: NextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
pathname: '/my-bucket/**',
},
],
},
};
export default config;
写得越具体越安全。
fill 模式
当你希望图片撑满父容器(父容器要 position: relative 且有尺寸):
<div style={{ position: 'relative', width: 320, height: 180 }}>
<Image src="/cover.jpg" alt="封面" fill sizes="320px" />
</div>
sizes 帮 Next.js 选用最合适的响应式图源,务必提供。
性能建议
- 首屏的关键图像 加
priority,让它提前加载。 - 列表缩略图 用合理的
sizes,浏览器才能选出最优尺寸。 - 静态 import 能带来免费的 blur 占位,体验显著更好。
- 不要对装饰性图标使用
Image,直接<img>或 SVG 更轻量。