exportPathMap (已棄用)
此功能僅限於
next export使用,目前已棄用,建議改用pages中的getStaticPaths或app中的generateStaticParams。
exportPathMap 允許您指定請求路徑與頁面目的地的映射關係,供匯出時使用。在 exportPathMap 中定義的路徑也可在執行 next dev 時使用。
讓我們從一個範例開始,為具有以下頁面的應用程式建立自訂的 exportPathMap:
pages/index.jspages/about.jspages/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欄位無法與自動靜態優化頁面 (automatically statically optimized pages) 或getStaticProps頁面 一起使用,因為它們在建置時會被渲染為 HTML 檔案,且無法在next export期間提供額外的查詢資訊。
這些頁面隨後會被匯出為 HTML 檔案,例如 /about 會變成 /about.html。
exportPathMap 是一個 async 函式,接收 2 個參數:第一個是 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覆寫。我們不建議同時使用它們。