如何在 Next.js 中设置 i18n 翻译的 URL 路由?

Pri*_*ome 23 routes internationalization reactjs next.js

我正在使用Next.js i18n-routing来设置多语言网站。这非常有效。如果我在此创建一个文件,/pages/about.js将根据我的区域设置创建 URL,例如:

  • CN ->/about
  • 德->/de/about
  • 英语->/es/about

那就好了。

如果我想要每种语言的翻译 URL 路由怎么办?我被困在如何设置这个问题上......

  • CN ->/about
  • 德->/de/uber-uns
  • 英语->/es/nosotros

jul*_*ves 31

您可以通过rewrites在文件中利用来实现翻译后的 URL 路由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
            }
        ]
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,如果您希望在客户端导航期间保持一致的路由行为,您可以在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
Run Code Online (Sandbox Code Playgroud)

然后在您的代码中使用TranslatedLink而不是。next/link

<TranslatedLink href='/about'>
    <a>Go to About page</a>
</TranslatedLink>
Run Code Online (Sandbox Code Playgroud)

请注意,您可以重用该pathTranslations对象来动态生成rewrites数组,next.config.js并为翻译后的 URL 提供单一的真实来源。

  • 我正在研究重写,但管理 9 种语言和 100 个页面的重写似乎有点笨拙。此外,你还有动态路由,这使得重写的事情变得越来越复杂。 (4认同)
  • 当然,这是一个简单的解决方案,但扩展性不佳。您可能需要考虑添加[自定义服务器](https://nextjs.org/docs/advanced-features/custom-server)以获得更复杂和可扩展的解决方案。 (2认同)