跳至內容

basePath

要在網域的子路徑下部署 Next.js 應用程式,您可以使用 basePath 設定選項。

basePath 允許您設定應用程式路徑的前綴。例如,要使用 /docs 取代 ''(空字串,預設值),請開啟 next.config.js 並新增 basePath 設定。

next.config.js
module.exports = {
  basePath: '/docs',
}

注意事項:此值必須在建置時設定,且在沒有重新建置的情況下無法更改,因為該值已內嵌於客戶端套件中。

當使用 next/linknext/router 連結到其他頁面時,basePath 將會自動套用。

例如,當 basePath 設定為 /docs 時,使用 /about 將會自動變成 /docs/about

export default function HomePage() {
  return (
    <>
      <Link href="/about">About Page</Link>
    </>
  )
}

輸出 HTML

<a href="/docs/about">About Page</a>

這確保了您在更改 basePath 值時,不需要更改應用程式中的所有連結。

圖片

當使用 next/image 元件時,您需要在 src 前面加上 basePath

例如,當 basePath 設定為 /docs 時,使用 /docs/me.png 將會正確地提供您的圖片。

import Image from 'next/image'
 
function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image
        src="/docs/me.png"
        alt="Picture of the author"
        width={500}
        height={500}
      />
      <p>Welcome to my homepage!</p>
    </>
  )
}
 
export default Home