basePath
要将 Next.js 应用程序部署到域的子路径下,您可以使用basePath 配置选项。
basePath 允许您为应用程序设置路径前缀。例如,要使用/docs 而不是''(空字符串,默认值),请打开next.config.js 并添加basePath 配置
next.config.js
module.exports = {
basePath: '/docs',
}**须知**:此值必须在构建时设置,并且在不重新构建的情况下无法更改,因为该值已内联到客户端捆绑包中。
链接
使用next/link 和next/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这有帮助吗?