跳到內容

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