Next.js 圖像和字體優(yōu)化:新手指南

2025-03-20 10:37 更新

如何優(yōu)化圖像和字體

Next.js 自帶自動圖像和字體優(yōu)化功能,可提升性能和用戶體驗。本頁將指導(dǎo)你如何開始使用這些功能。

處理靜態(tài)資源

你可以將靜態(tài)文件(如圖像和字體)存儲在根目錄下的 public 文件夾中。public 文件夾中的文件可以通過從基礎(chǔ) URL(/)開始的路徑在代碼中引用。

Next.js中文教程-處理靜態(tài)資源

優(yōu)化圖像

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

  • 尺寸優(yōu)化:根據(jù)設(shè)備自動提供正確尺寸的圖像,使用現(xiàn)代圖像格式(如 WebP)。
  • 視覺穩(wěn)定性:在圖像加載時自動防止布局偏移。
  • 更快的頁面加載速度:使用瀏覽器原生懶加載功能,僅在圖像進入視口時加載圖像,并可選提供模糊占位符。
  • 資源靈活性:按需調(diào)整圖像大小,即使圖像存儲在遠程服務(wù)器上。

要開始使用 <Image>,從 next/image 導(dǎo)入它,并在組件中渲染。

import Image from 'next/image'


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

src 屬性可以是本地或遠程圖像。

本地圖像

要使用本地圖像,從 public 文件夾中導(dǎo)入 .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 會根據(jù)導(dǎo)入的文件自動確定圖像的固有 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 在構(gòu)建過程中無法訪問遠程文件,因此需要手動提供 widthheight 和可選的 blurDataURL 屬性。widthheight 屬性用于推斷圖像的正確比例,并避免圖像加載時的布局偏移。

然后,為了安全地允許來自遠程服務(wù)器的圖像,需要在 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

優(yōu)化字體

next/font 模塊會自動優(yōu)化字體并移除外網(wǎng)請求,提升隱私和性能。

它包括 內(nèi)置自動自托管,適用于任何字體文件。這意味著你可以最優(yōu)地加載網(wǎng)絡(luò)字體,而不會出現(xiàn)布局偏移。

要開始使用 next/font,從 next/font/localnext/font/google 導(dǎo)入它,將其作為函數(shù)調(diào)用,并設(shè)置要應(yīng)用字體的元素的 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 字體。字體包含在部署中,并從與部署相同的域提供服務(wù),這意味著當用戶訪問你的網(wǎng)站時,瀏覽器不會向 Google 發(fā)送請求。

要開始使用 Google 字體,從 next/font/google 導(dǎo)入你選擇的字體:

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

我們建議使用可變字體,以獲得最佳性能和靈活性。但如果你不能使用可變字體,則需要指定一個權(quán)重:

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 導(dǎo)入字體,并在 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 可以是一個數(shù)組:

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 參考 ,了解有關(guān)本頁中提到的功能的更多信息。

  • 字體
    使用內(nèi)置的 'next/font' 加載器優(yōu)化加載 Web 字體。

  • 圖像
    使用內(nèi)置的“next/image”組件優(yōu)化 Next.js 應(yīng)用程序中的圖像。
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號