您可以通过在您的 next.config.js 文件中利用 rewrites 来实现已翻译的 URL 路由。
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 对象在 next.config.js 中动态生成 rewrites 数组,并为翻译后的 URL 提供单一真实来源。