要将 Next.js 应用程序部署到域名的子路径下,您可以使用 basePath 配置选项。
basePath 允许您为应用程序设置一个路径前缀。例如,要使用 /docs 而不是 ''(一个空字符串,默认值),请打开 next.config.js 并添加 basePath 配置:
module.exports = {
basePath: '/docs',
}须知:此值必须在构建时设置,并且无法在不重新构建的情况下更改,因为该值会内联到客户端 bundle 中。
当使用 next/link 和 next/router 链接到其他页面时,basePath 将会自动应用。
例如,当 basePath 设置为 /docs 时,使用 /about 将会自动变为 /zh-cn/docs/next.js/latest/about。
export default function HomePage() {
return (
<>
<Link href="/about">About Page</Link>
</>
)
}输出 HTML:
<a href="/zh-cn/docs/next.js/latest/about">About Page</a>这确保了您在更改 basePath 值时,无需更改应用程序中的所有链接。
当使用 next/image 组件时,您需要在 src 前面添加 basePath。
当使用 next/image 组件时,您需要在 src 前面添加 basePath。
例如,当 basePath 设置为 /docs 时,使用 /zh-cn/docs/next.js/latest/me.png 将会正确地提供您的图像。
import Image from 'next/image'
function Home() {
return (
<>
<h1>My Homepage</h1>
<Image
src="/zh-cn/docs/next.js/latest/me.png"
alt="Picture of the author"
width={500}
height={500}
/>
<p>Welcome to my homepage!</p>
</>
)
}
export default Home