您可以通过利用
rewrites
next.config.js
module.exports = {
i18n: {
locales: ['en', 'de', 'es'],
defaultLocale: 'en'
},
async rewrites() {
return [
{
source: '/de/uber-uns',
destination: '/de/about',
locale: false // Use `locale: false` so that the prefix matches the desired locale correctly
},
{
source: '/es/nosotros',
destination: '/es/about',
locale: false
}
]
}
}
此外,如果希望在客户端导航期间具有一致的路由行为,可以在
next/link
组件以确保显示已翻译的URL。
import { useRouter } from 'next/router'
import Link from 'next/link'
const pathTranslations = {
de: {
'/about': '/uber-uns'
},
es: {
'/about': '/sobrenos'
}
}
const TranslatedLink = ({ href, children }) => {
const { locale } = useRouter()
// Get translated route for non-default locales
const translatedPath = pathTranslations[locale]?.[href]
// Set `as` prop to change displayed URL in browser
const as = translatedPath ? `/${locale}${translatedPath}` : undefined
return (
<Link href={href} as={as}>
{children}
</Link>
)
}
export default TranslatedLink
然后使用
TranslatedLink
而不是
<TranslatedLink href='/about'>
<a>Go to About page</a>
</TranslatedLink>
请注意,您可以重用
pathTranslations
对象来动态生成
数组中的
next.config.js