跳到主要内容

图片优化

Next.js <Image> 组件扩展了 HTML <img> 元素,提供:

  • 尺寸优化: 自动为每个设备提供正确尺寸的图片,使用 WebP 等现代图片格式。
  • 视觉稳定性: 在图片加载时自动防止布局偏移
  • 更快的页面加载: 使用原生浏览器懒加载仅在图片进入视口时加载,带有可选的模糊占位符。
  • 资源灵活性: 按需调整图片大小,即使是存储在远程服务器上的图片。

要开始使用 <Image>,从 next/image 导入它并在组件中渲染。

app/page.tsx
import Image from 'next/image'

export default function Page() {
return <Image src="" alt="" />
}

src 属性可以是本地远程图片。

🎥 观看: 了解更多关于如何使用 next/imageYouTube (9 分钟)

本地图片

你可以将静态文件(如图片和字体)存储在根目录下名为 public 的文件夹中。public 内的文件然后可以从基础 URL (/) 开始被你的代码引用。

显示 app 和 public 文件夹的文件夹结构显示 app 和 public 文件夹的文件夹结构
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}
/>
)
}

如果图片是静态导入的,Next.js 将自动确定固有的 widthheight。这些值用于确定图片比例并在图片加载时防止累积布局偏移

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" // 加载时的可选模糊效果
/>
)
}

远程图片

要使用远程图片,你可以为 src 属性提供 URL 字符串。

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}
/>
)
}

由于 Next.js 在构建过程中无法访问远程文件,你需要手动提供 widthheight 和可选的 blurDataURL 属性。widthheight 用于推断图片的正确宽高比,并避免图片加载时的布局偏移。或者,你可以使用 fill 属性 使图片填充父元素的尺寸。

为了安全地允许来自远程服务器的图片,你需要在 next.config.js 中定义支持的 URL 模式列表。尽可能具体以防止恶意使用。例如,以下配置将只允许来自特定 AWS S3 存储桶的图片:

next.config.ts
import type { NextConfig } from 'next'

const config: NextConfig = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 's3.amazonaws.com',
port: '',
pathname: '/my-bucket/**',
search: '',
},
],
},
}

export default config