Skip to content

Next.js 配置优化 ⚙️

🎯 概述

通过优化 Next.js 配置,可以提升应用性能、开发体验和构建效率。

📦 next.config.js

基本配置

js
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  // 输出模式
  output: 'standalone',
  
  // 压缩
  compress: true,
  
  // 严格模式
  reactStrictMode: true,
  
  // SWC 压缩
  swcMinify: true,
}

module.exports = nextConfig

🚀 图片优化

js
module.exports = {
  images: {
    domains: ['example.com', 'cdn.example.com'],
    formats: ['image/avif', 'image/webp'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
    minimumCacheTTL: 60,
  },
}

📝 重定向和重写

重定向

js
module.exports = {
  async redirects() {
    return [
      {
        source: '/old-blog/:slug',
        destination: '/blog/:slug',
        permanent: true,
      },
      {
        source: '/docs',
        destination: '/docs/getting-started',
        permanent: false,
      },
    ]
  },
}

重写

js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'https://api.example.com/:path*',
      },
    ]
  },
}

🎨 头部配置

js
module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: [
          {
            key: 'X-Frame-Options',
            value: 'DENY',
          },
          {
            key: 'X-Content-Type-Options',
            value: 'nosniff',
          },
          {
            key: 'X-XSS-Protection',
            value: '1; mode=block',
          },
        ],
      },
      {
        source: '/api/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'no-store, must-revalidate',
          },
        ],
      },
    ]
  },
}

📊 Webpack 配置

js
module.exports = {
  webpack: (config, { isServer }) => {
    // 自定义 webpack 配置
    if (!isServer) {
      config.resolve.fallback = {
        fs: false,
        net: false,
        tls: false,
      }
    }
    
    return config
  },
}

🔧 实验性功能

js
module.exports = {
  experimental: {
    // 服务端操作
    serverActions: true,
    
    // 部分预渲染
    ppr: true,
    
    // 优化 CSS
    optimizeCss: true,
    
    // 优化包导入
    optimizePackageImports: ['lodash', 'date-fns'],
  },
}

📚 最佳实践

1. 环境特定配置

js
const isProd = process.env.NODE_ENV === 'production'

module.exports = {
  compress: isProd,
  reactStrictMode: !isProd,
  swcMinify: isProd,
}

2. 模块化配置

js
// next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})

module.exports = withBundleAnalyzer({
  // 配置
})

3. TypeScript 配置

js
module.exports = {
  typescript: {
    // 生产构建时忽略类型错误(不推荐)
    ignoreBuildErrors: false,
  },
}

🔗 相关资源


下一步:学习 Next.js 最佳实践