如何使用NextJS和next-i18next转换路由?

时间:2020-02-23 03:07:16

标签: reactjs translation next.js i18next

我正在使用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 /主页”和“ / pt-br / inicio”)。所以我想知道是否有更好的解决方案?

谢谢!

2 个答案:

答案 0 :(得分:7)

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

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

例如:您的 pages 文件夹将包含 2 页,homecontact

// 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', 
      }
    ]
  },
}

有关详细信息,请查看 Rewrites with i18n support 文章。

答案 1 :(得分:1)

有关解决方法,

我将组件页面创建为一个单独的模块,然后将其导入并导出到语言环境页面文件夹中。因此,我可以将1个组件重用为多种语言。

enter image description here

enter image description here

enter image description here