Next.js 图像和字体优化:新手指南

2025-03-20 10:37 更新

如何优化图像和字体

Next.js 自带自动图像和字体优化功能,可提升性能和用户体验。本页将指导你如何开始使用这些功能。

处理静态资源

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

Next.js中文教程-处理静态资源

优化图像

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

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

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

import Image from 'next/image'


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

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

本地图像

要使用本地图像,从 public 文件夹中导入 .jpg.png.webp 图像文件。

import Image from 'next/image'
import profilePic from './me.png'


export default function Page() {
  return (
    <Image
      src={profilePic}
      alt="作者的照片"
      // width={500} 自动提供
      // height={500} 自动提供
      // blurDataURL="data:..." 自动提供
      // placeholder="blur" // 可选的加载时模糊效果
    />
  )
}

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

远程图像

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

import Image from 'next/image'


export default function Page() {
  return (
    <Image
      src="https://s3.amazonaws.com/my-bucket/profile.png" rel="external nofollow" 
      alt="作者的照片"
      width={500}
      height={500}
    />
  )
}

由于 Next.js 在构建过程中无法访问远程文件,因此需要手动提供 widthheight 和可选的 blurDataURL 属性。widthheight 属性用于推断图像的正确比例,并避免图像加载时的布局偏移。

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

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 模块会自动优化字体并移除外网请求,提升隐私和性能。

它包括 内置自动自托管,适用于任何字体文件。这意味着你可以最优地加载网络字体,而不会出现布局偏移。

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

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 导入你选择的字体:

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

我们建议使用可变字体,以获得最佳性能和灵活性。但如果你不能使用可变字体,则需要指定一个权重:

import { Roboto } from 'next/font/google'


const roboto = Roboto({
  weight: '400',
  subsets: ['latin'],
})


export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="zh" className={roboto.className}>
      <body>{children}</body>
    </html>
  )
}

本地字体

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

import localFont from 'next/font/local'


const myFont = localFont({
  src: './my-font.woff2',
})


export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="zh" 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',
    },
  ],
})

API 参考

阅读 API 参考 ,了解有关本页中提到的功能的更多信息。

  • 字体
    使用内置的 'next/font' 加载器优化加载 Web 字体。

  • 图像
    使用内置的“next/image”组件优化 Next.js 应用程序中的图像。
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号