Next.js 15 在图片和字体优化方面有哪些内置功能?如何使用 next/image 和 next/font?

29 阅读3分钟

Next.js 15 在图片和字体优化方面有哪些内置功能?如何使用 next/image 和 next/font?

图片优化 (next/image)

核心功能

Next.js 15 的 next/image 组件提供了全面的图片优化功能:

import Image from 'next/image'

// 基础用法
function ProductCard({ product }) {
  return (
    <div>
      <Image
        src={product.image}
        alt={product.name}
        width={300}
        height={200}
        priority={false}
        placeholder="blur"
        blurDataURL="data:image/jpeg;base64,..."
      />
    </div>
  )
}

自动优化特性

  1. 格式转换
// 自动转换为 WebP/AVIF 格式
<Image
  src="/hero.jpg"
  alt="Hero image"
  width={800}
  height={600}
  // 自动选择最佳格式
/>
  1. 响应式图片
<Image
  src="/responsive.jpg"
  alt="Responsive image"
  fill
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
  style={{ objectFit: 'cover' }}
/>
  1. 懒加载
// 默认懒加载,viewport 外不加载
<Image
  src="/lazy.jpg"
  alt="Lazy loaded"
  width={400}
  height={300}
  loading="lazy" // 默认值
/>

// 关键图片优先加载
<Image
  src="/hero.jpg"
  alt="Hero"
  width={800}
  height={600}
  priority // 立即加载
/>

高级配置

// next.config.js
module.exports = {
  images: {
    domains: ['example.com', 'cdn.example.com'],
    formats: ['image/webp', 'image/avif'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
    minimumCacheTTL: 60,
    dangerouslyAllowSVG: true,
    contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
  },
}

字体优化 (next/font)

核心功能

Next.js 15 的 next/font 提供了字体优化和性能提升:

import { Inter, Roboto_Mono } from 'next/font/google'

// Google Fonts 优化
const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
})

const robotoMono = Roboto_Mono({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-roboto-mono',
})

export default function RootLayout({ children }) {
  return (
    <html lang="en" className={`${inter.variable} ${robotoMono.variable}`}>
      <body>{children}</body>
    </html>
  )
}

本地字体优化

import localFont from 'next/font/local'

const myFont = localFont({
  src: [
    {
      path: './fonts/MyFont-Regular.woff2',
      weight: '400',
      style: 'normal',
    },
    {
      path: './fonts/MyFont-Bold.woff2',
      weight: '700',
      style: 'normal',
    },
  ],
  variable: '--font-myfont',
  display: 'swap',
})

字体配置选项

const font = Inter({
  subsets: ['latin', 'cyrillic'],
  weight: ['400', '500', '600', '700'],
  style: ['normal', 'italic'],
  display: 'swap', // 防止字体闪烁
  preload: true, // 预加载
  fallback: ['system-ui', 'arial'], // 回退字体
  adjustFontFallback: true, // 自动调整回退字体
  variable: '--font-inter', // CSS 变量
})

性能优化策略

1. 图片优化策略

// 关键图片优先加载
function HeroSection() {
  return (
    <Image
      src="/hero.jpg"
      alt="Hero"
      width={1920}
      height={1080}
      priority
      quality={90}
      placeholder="blur"
      blurDataURL="data:image/jpeg;base64,..."
    />
  )
}

// 非关键图片懒加载
function ProductGrid({ products }) {
  return (
    <div className="grid">
      {products.map((product) => (
        <Image
          key={product.id}
          src={product.image}
          alt={product.name}
          width={300}
          height={200}
          loading="lazy"
          quality={75}
        />
      ))}
    </div>
  )
}

2. 字体优化策略

// 字体预加载
const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  preload: true,
  fallback: ['system-ui', 'arial'],
})

// CSS 变量使用
function MyComponent() {
  return (
    <div className="font-inter">
      <h1 className="text-4xl font-bold">标题</h1>
      <p className="text-base font-normal">正文内容</p>
    </div>
  )
}

实际应用场景

电商网站图片优化

function ProductPage({ product }) {
  return (
    <div>
      {/* 主图优先加载 */}
      <Image
        src={product.mainImage}
        alt={product.name}
        width={600}
        height={600}
        priority
        quality={90}
        placeholder="blur"
      />

      {/* 缩略图懒加载 */}
      <div className="thumbnails">
        {product.images.map((image, index) => (
          <Image
            key={index}
            src={image}
            alt={`${product.name} ${index + 1}`}
            width={100}
            height={100}
            loading="lazy"
            quality={60}
          />
        ))}
      </div>
    </div>
  )
}

博客字体优化

import { Inter, Source_Serif_Pro } from 'next/font/google'

const inter = Inter({
  subsets: ['latin'],
  display: 'swap',
  variable: '--font-inter',
})

const sourceSerif = Source_Serif_Pro({
  subsets: ['latin'],
  weight: ['400', '600'],
  display: 'swap',
  variable: '--font-serif',
})

export default function BlogLayout({ children }) {
  return (
    <html className={`${inter.variable} ${sourceSerif.variable}`}>
      <body>
        <header className="font-inter">
          <h1>博客标题</h1>
        </header>
        <main className="font-serif">{children}</main>
      </body>
    </html>
  )
}

性能监控

Core Web Vitals 优化

// 图片优化对 LCP 的影响
function OptimizedHero() {
  return (
    <Image
      src="/hero.jpg"
      alt="Hero"
      width={1920}
      height={1080}
      priority // 提升 LCP
      quality={90}
      placeholder="blur" // 减少 CLS
      sizes="100vw" // 响应式
    />
  )
}

// 字体优化减少 FOUT
const font = Inter({
  display: 'swap', // 防止字体闪烁
  preload: true, // 预加载关键字体
  fallback: ['system-ui'], // 快速回退
})

总结

Next.js 15 的图片和字体优化功能:

图片优化 (next/image)

  • 自动格式转换 (WebP/AVIF)
  • 响应式图片生成
  • 懒加载和优先级控制
  • 占位符和模糊效果
  • 性能监控集成

字体优化 (next/font)

  • Google Fonts 自动优化
  • 本地字体支持
  • 字体预加载和回退
  • 防止字体闪烁
  • CSS 变量集成

最佳实践

  • 关键图片使用 priority
  • 非关键图片使用 loading="lazy"
  • 字体使用 display: 'swap'
  • 合理设置 qualitysizes
  • 监控 Core Web Vitals 指标