图片优化
Next.js <Image> 组件扩展了 HTML <img> 元素,提供:
- 尺寸优化: 自动为每个设备提供正确尺寸的图片,使用 WebP 等现代图片格式。
- 视觉稳定性: 在图片加载时自动防止布局偏移。
- 更快的页面加载: 使用原生浏览器懒加载仅在图片进入视口时加载,带有可选的模糊占位符。
- 资源灵活性: 按需调整图片大小,即使是存储在远程服务器上的图片。
要开始使用 <Image>,从 next/image 导入它并在组件中渲染。
- TypeScript
- JavaScript
app/page.tsx
import Image from 'next/image'
export default function Page() {
return <Image src="" alt="" />
}
app/page.js
import Image from 'next/image'
export default function Page() {
return <Image src="" alt="" />
}
🎥 观看: 了解更多关于如何使用
next/image→ YouTube (9 分钟)。
本地图片
你可以将静态文件(如图片和字体)存储在根目录下名为 public 的文件夹中。public 内的文件然后可以从基础 URL (/) 开始被你的代码引用。


- TypeScript
- JavaScript
app/page.tsx
import Image from 'next/image'
export default function Page() {
return (
<Image
src="/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
app/page.js
import Image from 'next/image'
export default function Page() {
return (
<Image
src="/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
如果图片是静态导入的,Next.js 将自动确定固有的 width 和 height。这些值用于确定图片比例并在图片加载时防止累积布局偏移。
- TypeScript
- JavaScript
app/page.tsx
import Image from 'next/image'
import ProfileImage from './profile.png'
export default function Page() {
return (
<Image
src={ProfileImage}
alt="Picture of the author"
// width={500} 自动提供
// height={500} 自动提供
// blurDataURL="data:..." 自动提供
// placeholder="blur" // 加载时的可选模糊效果
/>
)
}
app/page.js
import Image from 'next/image'
import ProfileImage from './profile.png'
export default function Page() {
return (
<Image
src={ProfileImage}
alt="Picture of the author"
// width={500} 自动提供
// height={500} 自动提供
// blurDataURL="data:..." 自动提供
// placeholder="blur" // 加载时的可选模糊效果
/>
)
}
远程图片
要使用远程图片,你可以为 src 属性提供 URL 字符串。
- TypeScript
- JavaScript
app/page.tsx
import Image from 'next/image'
export default function Page() {
return (
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
app/page.js
import Image from 'next/image'
export default function Page() {
return (
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
由于 Next.js 在构建过程中无法访问远程文件,你需要手动提供 width