您可以利用以下方式实现翻译后的 URL 路由rewrites https://nextjs.org/docs/api-reference/next.config.js/rewrites#rewrites-with-i18n-support在你的next.config.js
file.
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
代替next/link
在你的代码中。
<TranslatedLink href='/about'>
<a>Go to About page</a>
</TranslatedLink>
请注意,您可以重复使用pathTranslations
动态生成对象rewrites
数组中的next.config.js
并且翻译后的 URL 具有单一的真实来源。