如何生成 Next.js 应用的静态导出

Next.js 允许您从静态站点或单页应用 (SPA) 开始,后续可选择升级使用需要服务器的功能。

当运行 next build 时,Next.js 会为每个路由生成一个 HTML 文件。通过将严格的 SPA 拆分为单独的 HTML 文件,Next.js 可以避免在客户端加载不必要的 JavaScript 代码,从而减少包体积并实现更快的页面加载。

由于 Next.js 支持这种静态导出,它可以部署在任何能够提供 HTML/CSS/JS 静态资源的 Web 服务器上。

配置

要启用静态导出,请在 next.config.js 中修改输出模式:

next.config.js
/**
 * @type {import('next').NextConfig}
 */
const nextConfig = {
  output: 'export',

  // 可选:将链接 `/me` 改为 `/me/` 并生成 `/me.html` -> `/me/index.html`
  // trailingSlash: true,

  // 可选:阻止自动将 `/me` 重定向到 `/me/`,保留原始 `href`
  // skipTrailingSlashRedirect: true,

  // 可选:修改输出目录 `out` -> `dist`
  // distDir: 'dist',
}

module.exports = nextConfig

运行 next build 后,Next.js 会创建一个包含应用 HTML/CSS/JS 资源的 out 文件夹。

您可以使用 getStaticPropsgetStaticPathspages 目录中的每个页面(或更多动态路由)生成 HTML 文件。

支持的功能

构建静态站点所需的大多数核心 Next.js 功能都得到支持,包括:

图片优化

通过 next/image 实现的图片优化可以在静态导出中使用,只需在 next.config.js 中定义自定义图片加载器。例如,您可以使用 Cloudinary 等服务优化图片:

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'export',
  images: {
    loader: 'custom',
    loaderFile: './my-loader.ts',
  },
}

module.exports = nextConfig

这个自定义加载器将定义如何从远程源获取图片。例如,以下加载器将为 Cloudinary 构建 URL:

export default function cloudinaryLoader({
  src,
  width,
  quality,
}: {
  src: string
  width: number
  quality?: number
}) {
  const params = ['f_auto', 'c_limit', `w_${width}`, `q_${quality || 'auto'}`]
  return `https://res.cloudinary.com/demo/image/upload/${params.join(
    ','
  )}${src}`
}

然后您可以在应用中使用 next/image,定义 Cloudinary 中图片的相对路径:

import Image from 'next/image'

export default function Page() {
  return <Image alt="海龟" src="/turtles.jpg" width={300} height={300} />
}

不支持的功能

需要 Node.js 服务器或在构建过程中无法计算的动态逻辑的功能受支持:

部署

通过静态导出,Next.js 可以部署在任何能够提供 HTML/CSS/JS 静态资源的 Web 服务器上。

运行 next build 时,Next.js 会将静态导出生成到 out 文件夹中。例如,假设您有以下路由:

  • /
  • /blog/[id]

运行 next build 后,Next.js 将生成以下文件:

  • /out/index.html
  • /out/404.html
  • /out/blog/post-1.html
  • /out/blog/post-2.html

如果使用像 Nginx 这样的静态主机,您可以配置从传入请求到正确文件的重写:

nginx.conf
server {
  listen 80;
  server_name acme.com;

  root /var/www/out;

  location / {
      try_files $uri $uri.html $uri/ =404;
  }

  # 当 `trailingSlash: false` 时需要此配置
  # 当 `trailingSlash: true` 时可以省略
  location /blog/ {
      rewrite ^/blog/(.*)$ /blog/$1.html break;
  }

  error_page 404 /404.html;
  location = /404.html {
      internal;
  }
}

版本历史

版本变更
v14.0.0next export 已被移除,改用 "output": "export"
v13.4.0应用路由(稳定版)增加了增强的静态导出支持,包括使用 React 服务端组件和路由处理器。
v13.3.0next export 已弃用,改用 "output": "export"

On this page