匯出路徑映射
此功能僅限於
next export
使用,目前已建議改用pages
中的getStaticPaths
或app
中的generateStaticParams
。
範例
exportPathMap
可讓您指定請求路徑到頁面目的地的映射,以在匯出期間使用。在使用 next dev
時,exportPathMap
中定義的路徑也將可用。
讓我們從一個例子開始,為一個包含以下頁面的應用程式建立自訂的 exportPathMap
pages/index.js
pages/about.js
pages/post.js
打開 next.config.js
並加入以下 exportPathMap
設定
module.exports = {
exportPathMap: async function (
defaultPathMap,
{ dev, dir, outDir, distDir, buildId }
) {
return {
'/': { page: '/' },
'/about': { page: '/about' },
'/p/hello-nextjs': { page: '/post', query: { title: 'hello-nextjs' } },
'/p/learn-nextjs': { page: '/post', query: { title: 'learn-nextjs' } },
'/p/deploy-nextjs': { page: '/post', query: { title: 'deploy-nextjs' } },
}
},
}
注意事項:
exportPathMap
中的query
欄位無法與自動靜態優化頁面或getStaticProps
頁面一起使用,因為它們在建置時會渲染成 HTML 檔案,並且在next export
期間無法提供額外的查詢資訊。
這些頁面接著會被匯出為 HTML 檔案,例如,/about
會變成 /about.html
。
exportPathMap
是一個非同步函式 (async
function),它接收兩個參數:第一個是 defaultPathMap
,這是 Next.js 使用的預設映射。第二個參數是一個物件,包含:
dev
- 當exportPathMap
在開發環境中被呼叫時為true
。執行next export
時為false
。在開發環境中,exportPathMap
用於定義路由。dir
- 專案目錄的絕對路徑outDir
-out/
目錄的絕對路徑(可使用-o
設定)。當dev
為true
時,outDir
的值將為null
。distDir
-.next/
目錄的絕對路徑(可使用distDir
設定進行設定)buildId
- 產生的建置 ID
返回的物件是一個頁面映射,其中 key
是 pathname
,而 value
是一個接受以下欄位的物件:
page
:String
- 要渲染的pages
目錄內的頁面query
:Object
- 預渲染時傳遞給getInitialProps
的query
物件。預設為{}
匯出的
pathname
也可以是一個檔名(例如,/readme.md
),但如果其內容與.html
不同,您可能需要在提供其內容時將Content-Type
標頭設定為text/html
。
新增尾端斜線
可以將 Next.js 設定為將頁面匯出為 index.html
檔案並要求尾端斜線,/about
會變成 /about/index.html
,並且可透過 /about/
進行路由。這是 Next.js 9 之前的預設行為。
要切換回並新增尾端斜線,請開啟 next.config.js
並啟用 trailingSlash
設定
module.exports = {
trailingSlash: true,
}
自訂輸出目錄
next export
將使用 out
作為預設輸出目錄,您可以使用 -o
參數自訂此目錄,如下所示:
next export -o outdir
警告:使用
exportPathMap
已被棄用,並且會被pages
內的getStaticPaths
覆蓋。我們不建議同時使用它們。
這有幫助嗎?