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)入它,并在組件中渲染。

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

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

本地圖像

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

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

優(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。例如:

  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 字體。字體包含在部署中,并從與部署相同的域提供服務(wù),這意味著當(dāng)用戶訪問你的網(wǎng)站時,瀏覽器不會向 Google 發(fā)送請求。

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

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

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

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

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

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

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

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號