Next.js 图片和字体(一文讲透)

快速解决

使用 Next.js 的 next/image 组件优化图片加载,结合 next/font 自动加载字体资源,可显著提升页面性能和渲染速度。

常用方法

方法 使用场景 示例代码 说明
next/image 图片优化 import Image from 'next/image' 自动压缩/响应式图片
next/font 字体加载 const { fontFamily } = next/font/google({ name: 'Inter', weight: '400' }) 集成 Google 字体
ImageProps 自定义配置 quality={80} priority={true} 调整图片质量与优先级
localFont 本地字体 next/font/local({ src: './font.woff2' }) 加载项目内字体文件

详细说明

图片优化最佳实践

import Image from 'next/image'

// 使用 next/image 自动优化图片,指定宽度和高度
<Image 
  src="/static/logo.png" 
  alt="项目Logo" 
  width={200} 
  height={80} 
  // priority 属性确保首屏图片优先加载
  priority={true}
/>

字体加载配置

// pages/_app.js
import { Inter } from 'next/font/google'
import '../styles/globals.css'

const inter = Inter({ subsets: ['latin'] })

function MyApp({ Component, pageProps }) {
  // 将字体样式注入全局样式表
  return <main className={inter.className}><Component {...pageProps} /></main>
}

本地字体自定义

// utils/fonts.js
import { localFont } from 'next/font/local'

// 加载本地字体文件,指定权重和样式
const myFont = localFont({
  src: [
    { path: './MyFont-Regular.woff2', weight: '400' },
    { path: './MyFont-Bold.woff2', weight: '700' },
  ],
  variable: '--font-myfont' // 自定义字体变量名
})

export default myFont

高级技巧

动态字体加载方案

// 组件内按需加载字体
import dynamic from 'next/dynamic'

const GoogleFont = dynamic(() => import('next/font/google'), {
  ssr: false, // 服务端渲染时禁用字体预加载
  loading: () => <div className="fallback-font">加载中...</div>
})

图片延迟加载策略

<Image 
  src="/static/banner.jpg" 
  alt="横幅广告" 
  width={800} 
  height={400}
  // lazyLoading 仅加载可视区域内的图片
  loading="lazy" 
/>

CDN 配置优化

next.config.js 中添加:

module.exports = {
  images: {
    domains: ['your-cdn-domain.com'],
    // 启用远程图片缓存
    remotePatterns: [
      { 
        protocol: 'https',
        hostname: 'your-cdn-domain.com',
        port: '',
        pathname: '/**' 
      }
    ]
  }
}

常见问题

Q: 如何处理 SVG 图片? A: 使用 next/image 时需设置 type="image/svg+xml",或使用 next/font/local 直接导入 SVG 文件。

Q: 字体加载导致的 FOIT 问题? A: 通过设置 preconnect 属性连接字体服务器,或使用 next/font 内置的预加载功能。

Q: 静态资源路径错误? A: 确保图片存放在 public/ 目录,访问时使用绝对路径 /images/xxx.jpg

Q: 如何自定义 Google 字体子集? A: 在 subsets 参数中指定 ['latin']['cyrillic'],减少下载体积。

注意事项

  1. next/font 会自动添加 <link rel="preconnect">,无需手动配置
  2. 图片最大宽度建议不超过 1920px,避免过度压缩
  3. 避免在 loading="lazy" 图片上使用 priority 属性
  4. 字体文件建议使用 WOFF2 格式,兼容性和体积最优

总结

Next.js 图片和字体优化方案通过官方组件实现零配置性能提升,开发者只需关注资源路径和基础参数设置即可获得最佳加载体验。