Skip to main content

basePath

要在域的子路径下部署 Next.js 应用,你可以使用 basePath 配置选项。

¥To deploy a Next.js application under a sub-path of a domain you can use the basePath config option.

basePath 允许你设置应用的路径前缀。例如,要使用 /docs 而不是 ''(空字符串,默认值),请打开 next.config.js 并添加 basePath 配置:

¥basePath allows you to set a path prefix for the application. For example, to use /docs instead of '' (an empty string, the default), open next.config.js and add the basePath config:

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

很高兴知道:该值必须在构建时设置,并且在不重新构建的情况下无法更改,因为该值内联在客户端包中。

¥Good to know: This value must be set at build time and cannot be changed without re-building as the value is inlined in the client-side bundles.

¥Links

当使用 next/linknext/router 链接到其他页面时,将自动应用 basePath

¥When linking to other pages using next/link and next/router the basePath will be automatically applied.

例如,当 basePath 设置为 /docs 时,使用 /about 将自动变为 /docs/about

¥For example, using /about will automatically become /docs/about when basePath is set to /docs.

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

输出 html:

¥Output html:

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

这可确保你在更改 basePath 值时不必更改应用中的所有链接。

¥This makes sure that you don't have to change all links in your application when changing the basePath value.

图片

¥Images

使用 next/image 组件时,需要在 src 前面添加 basePath

¥When using the next/image component, you will need to add the basePath in front of src.

例如,当 basePath 设置为 /docs 时,使用 /docs/me.png 将正确提供你的图片。

¥For example, using /docs/me.png will properly serve your image when basePath is set to /docs.

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