Menu

How to create an static export of your Next.js application

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.config.js 中定义自定义图像加载器,可以在静态导出中使用 next/image 进行图像优化。例如,你可以使用 Cloudinary 等服务优化图像:

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

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

my-loader.ts
TypeScript
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 中图像的相对路径:

app/page.tsx
TypeScript
import Image from 'next/image'
 
export default function Page() {
  return <Image alt="turtles" 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.0App Router(稳定版)增加了增强的静态导出支持,包括使用 React 服务器组件和路由处理程序。
v13.3.0next export 已弃用,并替换为 "output": "export"