靜態匯出 (Static Exports)

Next.js 允許您從靜態網站或單頁應用程式 (SPA) 開始,之後可選擇升級使用需要伺服器的功能。

當執行 next build 時,Next.js 會為每個路由生成一個 HTML 檔案。透過將嚴格的 SPA 拆分成獨立的 HTML 檔案,Next.js 可以避免在客戶端載入不必要的 JavaScript 程式碼,減少套件大小並實現更快的頁面載入速度。

由於 Next.js 支援這種靜態匯出,因此可以部署並託管在任何能夠提供 HTML/CSS/JS 靜態資源的網頁伺服器上。

須知:我們建議使用應用程式路由 (App Router) 以獲得增強的靜態匯出支援。

設定

要啟用靜態匯出,請在 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 會產生一個 out 資料夾,其中包含應用程式的 HTML/CSS/JS 資源。

您可以使用 getStaticPropsgetStaticPathspages 目錄中的每個頁面生成 HTML 檔案(或為動態路由生成更多檔案)。

支援的功能

構建靜態網站所需的大多數核心 Next.js 功能都受到支援,包括:

圖片優化 (Image Optimization)

透過在 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:

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="turtles" src="/turtles.jpg" width={300} height={300} />
}

不支援的功能

需要 Node.js 伺服器或在構建過程中無法計算的動態邏輯的功能受支援:

部署

使用靜態匯出時,Next.js 可以部署並託管在任何能夠提供 HTML/CSS/JS 靜態資源的網頁伺服器上。

執行 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應用程式路由 (App Router) 穩定版新增增強的靜態匯出支援,包括使用 React 伺服器元件和路由處理器。
v13.3.0next export 已被棄用,改用 "output": "export"

On this page