跳到內容

靜態匯出

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 資源。

支援的功能

Next.js 的核心設計旨在支援靜態匯出。

伺服器元件

當您執行 next build 以產生靜態匯出時,在 app 目錄內使用的伺服器元件將在建置期間執行,類似於傳統的靜態網站產生。

產生的元件將被渲染為靜態 HTML,用於初始頁面載入,以及靜態有效負載,用於路由之間的用戶端導航。當使用靜態匯出時,您的伺服器元件不需要任何變更,除非它們使用動態伺服器函式

app/page.tsx
export default async function Page() {
  // This fetch will run on the server during `next build`
  const res = await fetch('https://api.example.com/...')
  const data = await res.json()
 
  return <main>...</main>
}

用戶端元件

如果您想在用戶端執行資料抓取,您可以使用用戶端元件與 SWR 來記憶請求。

app/other/page.tsx
'use client'
 
import useSWR from 'swr'
 
const fetcher = (url: string) => fetch(url).then((r) => r.json())
 
export default function Page() {
  const { data, error } = useSWR(
    `https://jsonplaceholder.typicode.com/posts/1`,
    fetcher
  )
  if (error) return 'Failed to load'
  if (!data) return 'Loading...'
 
  return data.title
}

由於路由轉換發生在用戶端,因此其行為類似於傳統的 SPA。例如,以下索引路由允許您在用戶端導航到不同的文章

app/page.tsx
import Link from 'next/link'
 
export default function Page() {
  return (
    <>
      <h1>Index Page</h1>
      <hr />
      <ul>
        <li>
          <Link href="/post/1">Post 1</Link>
        </li>
        <li>
          <Link href="/post/2">Post 2</Link>
        </li>
      </ul>
    </>
  )
}

圖片最佳化

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

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

路由處理器

當執行 next build 時,路由處理器將渲染靜態回應。僅支援 GET HTTP 動詞。這可用於從快取或未快取的資料產生靜態 HTML、JSON、TXT 或其他檔案。例如

app/data.json/route.ts
export async function GET() {
  return Response.json({ name: 'Lee' })
}

上面的檔案 app/data.json/route.ts 將在 next build 期間渲染為靜態檔案,產生包含 { name: 'Lee' }data.json

如果您需要從傳入的請求中讀取動態值,則無法使用靜態匯出。

瀏覽器 API

用戶端元件在 next build 期間預先渲染為 HTML。由於像 windowlocalStoragenavigator 這樣的 Web API 在伺服器上不可用,因此您需要僅在瀏覽器中執行時安全地存取這些 API。例如

'use client';
 
import { useEffect } from 'react';
 
export default function ClientComponent() {
  useEffect(() => {
    // You now have access to `window`
    console.log(window.innerHeight);
  }, [])
 
  return ...;
}

不支援的功能

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

嘗試在 next dev 中使用任何這些功能將導致錯誤,類似於將根版面配置中的 dynamic 選項設定為 error

export const dynamic = 'error'

部署

透過靜態匯出,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 這樣的靜態主機,您可以將來自傳入請求的 rewrites 設定為正確的檔案

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.0next export 已移除,改用 "output": "export"
v13.4.0App Router (穩定版) 增加了強化的靜態匯出支援,包括使用 React 伺服器元件和路由處理器。
v13.3.0next export 已棄用,並由 "output": "export" 取代