如何使用 NextJS 和 next-i18next 翻译路由?

Ale*_*iva 19 translation i18next reactjs next.js

我正在使用 next.JS 和包 next-i18next 构建一个多语言网站。它进展顺利,除了一件事我不确定什么是最好的方法。我希望我的静态路由也将被翻译(不仅是页面内容),例如:

example.com/en/home -> example.com/pt-br/inicio

example.com/en/contact -> example.com/pt-br/contato

我知道我可以创建目录 (en/pt-br) 并在其中插入页面(例如:home.js、contact.js 等在“/en/”和 inicio.js、contato.js 等在“/”中pt-br/"),这样在用户访问这些页面时很容易定义语言,但我需要创建 2 个几乎所有相同内容的文件(例如:“/en/home”和“/pt-br/inicio”)。所以我想知道是否有更好的解决方案?

谢谢!

fel*_*osh 8

您可以使用Next.js rewrites,而不是为多种语言复制同一页面,这会损害构建性能并且如果您需要支持超过 5 个语言,则不会扩展。

它是在 中引入的v9.5,并允许您重写特定页面的路径,在您的示例中,您可以为主要语言创建页面,以及您可以添加重写支持的所有辅助语言。结合i18n 子路径(在 中引入v10),接下来将处理语言环境部分 ( /en// /pt-br/)。

例如:您的pages文件夹将包含 2 页,home& contact

// next.config.js

module.exports = {
  i18n: {
    locales: ['en', 'pt-br'],
    defaultLocale: 'en',
  },

  async rewrites() {
    return [
      {
        source: '/inicio', // automatically handles all locales
        destination: '/home', // automatically passes the locale on
      },
      {
        source: '/contato', 
        destination: '/contact', 
      }
    ]
  },
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看使用 i18n 支持文章重写