如何优化图片

Next.js 的 <Image> 组件扩展了 HTML <img> 元素,提供以下功能:

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

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

import Image from 'next/image'

export default function Page() {
  return <Image src="" alt="" />
}
import Image from 'next/image'

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

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

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

本地图片

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

展示 app 和 public 文件夹结构的示意图
import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="作者照片"
      width={500}
      height={500}
    />
  )
}
import Image from 'next/image'

export default function Page() {
  return (
    <Image
      src="/profile.png"
      alt="作者照片"
      width={500}
      height={500}
    />
  )
}

静态导入图片

您也可以导入并使用本地图片文件。Next.js 会根据导入的文件自动确定图片的固有 widthheight。这些值用于确定图片比例并在加载时防止累积布局偏移 (CLS)

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

在这种情况下,Next.js 期望 app/profile.png 文件是可用的。

远程图片

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

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}
    />
  )
}
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 在构建过程中无法访问远程文件,您需要手动提供 widthheight 和可选的 blurDataURL 属性。widthheight 用于推断正确的图片宽高比,避免图片加载时的布局偏移。

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

import type { NextConfig } from 'next'

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

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