跳至內容

匯出路徑映射

此功能僅限於 next export 使用,目前已建議改用 pages 中的 getStaticPathsapp 中的 generateStaticParams

範例

exportPathMap 可讓您指定請求路徑到頁面目的地的映射,以在匯出期間使用。在使用 next dev 時,exportPathMap 中定義的路徑也將可用。

讓我們從一個例子開始,為一個包含以下頁面的應用程式建立自訂的 exportPathMap

  • pages/index.js
  • pages/about.js
  • pages/post.js

打開 next.config.js 並加入以下 exportPathMap 設定

next.config.js
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 設定)。當 devtrue 時,outDir 的值將為 null
  • distDir - .next/ 目錄的絕對路徑(可使用distDir 設定進行設定)
  • buildId - 產生的建置 ID

返回的物件是一個頁面映射,其中 keypathname,而 value 是一個接受以下欄位的物件:

  • pageString - 要渲染的 pages 目錄內的頁面
  • queryObject - 預渲染時傳遞給 getInitialPropsquery 物件。預設為 {}

匯出的 pathname 也可以是一個檔名(例如,/readme.md),但如果其內容與 .html 不同,您可能需要在提供其內容時將 Content-Type 標頭設定為 text/html

新增尾端斜線

可以將 Next.js 設定為將頁面匯出為 index.html 檔案並要求尾端斜線,/about 會變成 /about/index.html,並且可透過 /about/ 進行路由。這是 Next.js 9 之前的預設行為。

要切換回並新增尾端斜線,請開啟 next.config.js 並啟用 trailingSlash 設定

next.config.js
module.exports = {
  trailingSlash: true,
}

自訂輸出目錄

next export 將使用 out 作為預設輸出目錄,您可以使用 -o 參數自訂此目錄,如下所示:

終端機
next export -o outdir

警告:使用 exportPathMap 已被棄用,並且會被 pages 內的 getStaticPaths 覆蓋。我們不建議同時使用它們。