跳到内容
App Router入门图像优化

图像优化

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 的文件夹下。然后,您的代码可以从基本 URL (/) 开始引用 public 中的文件。

Folder structure showing app and public folders
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} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

远程图像

要使用远程图像,您可以为 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

API 参考

请参阅 API 参考以获取 Next.js Image 的完整功能集。