跳至內容

靜態匯出

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',
 
  // Optional: Change links `/me` -> `/me/` and emit `/me.html` -> `/me/index.html`
  // trailingSlash: true,
 
  // Optional: Prevent automatic `/me` -> `/me/`, instead preserve `href`
  // skipTrailingSlashRedirect: true,
 
  // Optional: Change the output directory `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。

my-loader.ts
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
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;
  }
 
  # This is necessary when `trailingSlash: false`.
  # You can omit this when `trailingSlash: true`.
  location /blog/ {
      rewrite ^/blog/(.*)$ /blog/$1.html break;
  }
 
  error_page 404 /404.html;
  location = /404.html {
      internal;
  }
}

版本歷史記錄

版本變更
v14.0.0已移除 next export,改用 "output": "export"
v13.4.0應用程式路由器(穩定版)新增了增強的靜態匯出支援,包括使用 React 伺服器元件和路由處理程式。
v13.3.0next export 已被棄用,並由 "output": "export" 取代。