如何建立 Next.js 應用程式的靜態匯出

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

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

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

配置

要啟用靜態匯出,請修改 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 功能都受到支援,包括:

圖片最佳化

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

On this page