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

不支援的功能

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

部署

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

執行 next build 時,Next.js 會將靜態匯出生成到 out 資料夾中。不再需要 next export。例如,假設您有以下路由:

  • /
  • /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;
  }
}

版本歷史

版本變更
v13.4.0App Router (穩定版) 增加了增強的靜態匯出支援,包括使用 React 伺服器元件和路由處理器。
v13.3.0next export 已被棄用,改為使用 "output": "export"

On this page