Image Optimization
Next.js 的 <Image> 组件扩展了 HTML <img> 元素,提供了以下功能:
- 尺寸优化: 使用 WebP 等现代图片格式,自动为每个设备提供正确尺寸的图片。
- 视觉稳定性: 在图片加载时自动防止布局偏移。
- 更快的页面加载: 使用原生浏览器懒加载,仅在图片进入视口时加载,并可选模糊占位符。
- 资源灵活性: 按需调整图片大小,甚至可以调整存储在远程服务器上的图片。
要开始使用 <Image>,从 next/image 导入它并在你的组件中渲染。
app/page.tsx
TypeScript
import Image from 'next/image'
export default function Page() {
return <Image src="" alt="" />
}🎥 观看: 了解更多关于如何使用
next/image→ YouTube(9 分钟)。
本地图片
你可以在根目录下名为 public 的文件夹中存储静态文件,如图片和字体。public 内的文件可以从基础 URL(/)开始被你的代码引用。
app/page.tsx
TypeScript
import Image from 'next/image'
export default function Page() {
return (
<Image
src="/profile.png"
alt="作者的照片"
width={500}
height={500}
/>
)
}如果图片是静态导入的,Next.js 将自动确定固有的 width 和 height。这些值用于确定图片比例,并在图片加载时防止累积布局偏移。
app/page.tsx
TypeScript
import Image from 'next/image'
import ProfileImage from './profile.png'
export default function Page() {
return (
<Image
src={ProfileImage}
alt="作者的照片"
// width={500} 自动提供
// height={500} 自动提供
// blurDataURL="data:..." 自动提供
// placeholder="blur" // 可选的加载时模糊效果
/>
)
}远程图片
要使用远程图片,你可以为 src 属性提供一个 URL 字符串。
app/page.tsx
TypeScript
import Image from 'next/image'
export default function Page() {
return (
<Image
src="https://s3.amazonaws.com/my-bucket/profile.png"
alt="作者的照片"
width={500}
height={500}
/>
)
}由于 Next.js 在构建过程中无法访问远程文件,你需要手动提供 width、height 和可选的 blurDataURL 属性。width 和 height 用于推断图片的正确宽高比,并避免图片加载时的布局偏移。或者,你可以使用 fill 属性使图片填充父元素的大小。
为了安全地允许来自远程服务器的图片,你需要在 next.config.js 中定义支持的 URL 模式列表。尽可能具体以防止恶意使用。例如,以下配置将仅允许来自特定 AWS S3 存储桶的图片:
next.config.ts
TypeScript
import type { NextConfig } from 'next'
const config: NextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
port: '',
pathname: '/my-bucket/**',
search: '',
},
],
},
}
export default config