靜態匯出
Next.js 讓您可以從靜態網站或單頁應用程式 (SPA) 開始,之後再選擇性地升級以使用需要伺服器的功能。
執行 next build
時,Next.js 會為每個路由生成一個 HTML 檔案。藉由將嚴格的 SPA 拆分為個別的 HTML 檔案,Next.js 可以避免在客戶端載入不必要的 JavaScript 程式碼,從而減少套件大小並加快頁面載入速度。
由於 Next.js 支援此靜態匯出,因此可以將其部署並託管在任何可以提供 HTML/CSS/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 以進行初始頁面載入,並產生靜態有效負載以供客戶端在路由之間導覽。使用靜態匯出時,您的伺服器元件不需要任何更改,除非它們使用動態伺服器函式。
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>
}
客戶端元件 來記憶請求。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
}
'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。例如,以下索引路由允許您在客戶端上導覽到不同的文章。
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 之類的服務來優化影像。
/** @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} />
}
路由處理器
執行 next build
時,路由處理器將會渲染靜態回應。僅支援 GET
HTTP 方法。這可以用於從快取或未快取的資料生成靜態 HTML、JSON、TXT 或其他檔案。例如:
export async function GET() {
return Response.json({ name: 'Lee' })
}
上述檔案 app/data.json/route.ts
將在 next build
期間渲染為靜態檔案,產生包含 { name: 'Lee' }
的 data.json
。
如果您需要從傳入請求中讀取動態值,則無法使用靜態匯出。
瀏覽器 API
客戶端組件在 next build
期間會預先渲染為 HTML。由於網頁 APIwindow
、localStorage
和 navigator
在伺服器上無法使用,因此您需要僅在瀏覽器中運行時安全地存取這些 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 伺服器或是在建置過程中無法計算的動態邏輯之功能皆**不**支援。
- 使用
dynamicParams: true
的動態路由 - 未使用
generateStaticParams()
的動態路由 - 依賴 Request 的路由處理器
- Cookie
- 重寫
- 重新導向
- 標頭
- 中介軟體
- 增量靜態再生
- 使用預設
loader
的圖片最佳化 - 草稿模式
- 伺服器動作
嘗試在 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 這樣的靜態主機,您可以設定從傳入請求到正確檔案的重寫規則。
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.0 | next export 已棄用,並由 "output": "export" 取代。 |
這有幫助嗎?