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

2025-03-20 10:37 更新

如何优化图像和字体

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

处理静态资源

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

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

优化图像

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

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

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

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

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

本地图像

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

  1. import Image from 'next/image'
  2. import profilePic from './me.png'
  3. export default function Page() {
  4. return (
  5. <Image
  6. src={profilePic}
  7. alt="作者的照片"
  8. // width={500} 自动提供
  9. // height={500} 自动提供
  10. // blurDataURL="data:..." 自动提供
  11. // placeholder="blur" // 可选的加载时模糊效果
  12. />
  13. )
  14. }

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

远程图像

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

  1. import Image from 'next/image'
  2. export default function Page() {
  3. return (
  4. <Image
  5. src="https://s3.amazonaws.com/my-bucket/profile.png" rel="external nofollow"
  6. alt="作者的照片"
  7. width={500}
  8. height={500}
  9. />
  10. )
  11. }

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

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

  1. import { NextConfig } from 'next'
  2. const config: NextConfig = {
  3. images: {
  4. remotePatterns: [
  5. {
  6. protocol: 'https',
  7. hostname: 's3.amazonaws.com',
  8. port: '',
  9. pathname: '/my-bucket/**',
  10. search: '',
  11. },
  12. ],
  13. },
  14. }
  15. export default config

优化字体

next/font 模块会自动优化字体并移除外网请求,提升隐私和性能。

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

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

  1. import { Geist } from 'next/font/google'
  2. const geist = Geist({
  3. subsets: ['latin'],
  4. })
  5. export default function Layout({ children }: { children: React.ReactNode }) {
  6. return (
  7. <html lang="en" className={geist.className}>
  8. <body>{children}</body>
  9. </html>
  10. )
  11. }

Google 字体

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

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

  1. import { Geist } from 'next/font/google'
  2. const geist = Geist({
  3. subsets: ['latin'],
  4. })
  5. export default function RootLayout({
  6. children,
  7. }: {
  8. children: React.ReactNode
  9. }) {
  10. return (
  11. <html lang="en" className={geist.className}>
  12. <body>{children}</body>
  13. </html>
  14. )
  15. }

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

  1. import { Roboto } from 'next/font/google'
  2. const roboto = Roboto({
  3. weight: '400',
  4. subsets: ['latin'],
  5. })
  6. export default function RootLayout({
  7. children,
  8. }: {
  9. children: React.ReactNode
  10. }) {
  11. return (
  12. <html lang="zh" className={roboto.className}>
  13. <body>{children}</body>
  14. </html>
  15. )
  16. }

本地字体

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

  1. import localFont from 'next/font/local'
  2. const myFont = localFont({
  3. src: './my-font.woff2',
  4. })
  5. export default function RootLayout({
  6. children,
  7. }: {
  8. children: React.ReactNode
  9. }) {
  10. return (
  11. <html lang="zh" className={myFont.className}>
  12. <body>{children}</body>
  13. </html>
  14. )
  15. }

如果你想为一个字体家族使用多个文件,src 可以是一个数组:

  1. const roboto = localFont({
  2. src: [
  3. {
  4. path: './Roboto-Regular.woff2',
  5. weight: '400',
  6. style: 'normal',
  7. },
  8. {
  9. path: './Roboto-Italic.woff2',
  10. weight: '400',
  11. style: 'italic',
  12. },
  13. {
  14. path: './Roboto-Bold.woff2',
  15. weight: '700',
  16. style: 'normal',
  17. },
  18. {
  19. path: './Roboto-BoldItalic.woff2',
  20. weight: '700',
  21. style: 'italic',
  22. },
  23. ],
  24. })

API 参考

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

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

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

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号