跳转至

图像优化

原文地址:https://nextjs.org/docs/app/getting-started/images

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

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

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

app/page.tsx
1
2
3
4
5
import Image from 'next/image'

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

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

1. 本地图片

您可以将静态文件(例如图像和字体)存储在根目录中名为 public 文件夹下。然后,您的代码可以从基本 URL ( / ) 开始引用 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} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

2. 远程图片

由于 Next.js 在构建过程中无法访问远程文件,因此您需要手动提供 widthheight 和可选的 blurDataURL 属性。 widthheight 用于推断图像的正确纵横比,并避免加载图像时发生布局偏移。或者,您可以使用 fill 属性使图像填充父元素的大小。

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

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

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

export default config`