跳到内容
App Router开始使用图像和字体

如何优化图像和字体

Next.js 自带自动图像和字体优化功能,以获得更好的性能和用户体验。本页将指导您如何开始使用它们。

处理静态资源

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

Folder structure showing app and public folders

优化图像

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 属性可以是本地远程图像。

本地图像

要使用本地图像,请从您的public 文件夹import 您的 .jpg.png.webp 图像文件。

app/page.tsx
import Image from 'next/image'
import profilePic from './me.png'
 
export default function Page() {
  return (
    <Image
      src={profilePic}
      alt="Picture of the author"
      // width={500} automatically provided
      // height={500} automatically provided
      // blurDataURL="data:..." automatically provided
      // placeholder="blur" // Optional blur-up while loading
    />
  )
}

Next.js 将根据导入的文件自动确定图像的固有widthheight。这些值用于确定图像比例,并防止在图像加载时出现 累积布局偏移

远程图像

要使用远程图像,您可以为 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 属性用于推断图像的正确宽高比,并避免图像加载时的布局偏移。

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

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

优化字体

next/font 模块自动优化您的字体,并删除外部网络请求,以提高隐私性和性能。

它包括 内置的自动自托管 功能,适用于任何字体文件。这意味着您可以最佳地加载 Web 字体,而不会发生布局偏移。

要开始使用 next/font,请从 next/font/localnext/font/google 导入它,将其作为带有适当选项的函数调用,并设置要应用字体的元素的 className。例如

app/layout.tsx
import { Geist } from 'next/font/google'
 
const geist = Geist({
  subsets: ['latin'],
})
 
export default function Layout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={geist.className}>
      <body>{children}</body>
    </html>
  )
}

Google 字体

您可以自动自托管任何 Google 字体。字体包含在部署中,并从与您的部署相同的域提供服务,这意味着当用户访问您的网站时,浏览器不会向 Google 发送请求。

要开始使用 Google 字体,请从 next/font/google 导入您选择的字体

app/layout.tsx
import { Geist } from 'next/font/google'
 
const geist = Geist({
  subsets: ['latin'],
})
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={geist.className}>
      <body>{children}</body>
    </html>
  )
}

我们建议使用 可变字体 以获得最佳性能和灵活性。但是,如果您无法使用可变字体,则需要指定粗细

app/layout.tsx
import { Roboto } from 'next/font/google'
 
const roboto = Roboto({
  weight: '400',
  subsets: ['latin'],
})
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={roboto.className}>
      <body>{children}</body>
    </html>
  )
}

本地字体

要使用本地字体,请从 next/font/local 导入您的字体,并在public 文件夹中指定本地字体文件的 src

app/layout.tsx
import localFont from 'next/font/local'
 
const myFont = localFont({
  src: './my-font.woff2',
})
 
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={myFont.className}>
      <body>{children}</body>
    </html>
  )
}

如果您想为单个字体系列使用多个文件,则 src 可以是一个数组

const roboto = localFont({
  src: [
    {
      path: './Roboto-Regular.woff2',
      weight: '400',
      style: 'normal',
    },
    {
      path: './Roboto-Italic.woff2',
      weight: '400',
      style: 'italic',
    },
    {
      path: './Roboto-Bold.woff2',
      weight: '700',
      style: 'normal',
    },
    {
      path: './Roboto-BoldItalic.woff2',
      weight: '700',
      style: 'italic',
    },
  ],
})