Next.js多语言站点的URL结构。

3

我正在将我的应用程序迁移到Next.js。目前,我的url结构如下:

www.example.com/ <-- English
www.example.com/de <-- German
www.example.com/page <-- English
www.example.com/de/page <-- German

我的英文网站在URL中没有语言信息。如果有人使用带有“en”的URL访问该网站,则会被重定向。

在 Next.js 中如何实现此功能?似乎在/pages目录下始终需要两个文件(即“[language].js”和“index.js”)并不是正确的解决方案。


你找到解决方案了吗?可以帮我一下吗? - user1228739
3个回答

6

使用NextJS 10,您可以本地化地实现此操作 您的next.config.js应如下所示:

module.exports = {
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
}

defaultLocalewww.example.com/ 网站的语言。

然后您可以使用像next-i18next这样的库来存储翻译。


5
从 Next.js 9.4 开始,有一个实验性功能 "自定义路由"。这提供了更优雅的解决方案。请参考此处的讨论:https://github.com/zeit/next.js/issues/9081 使用示例:
// next.config.js
module.exports = {
  async rewrites() {
    return [
      // Basic `path-to-regexp` usage
      // Query object shape: { id: string }
      { source: "/user/:id", destination: "/user_profile" },

      // Optional Language
      // Query object shape: { lang?: string }
      { source: "/:lang(en|es)?/about", destination: "/about" },

      // Advanced rewrite
      // Query object shape: { id: string } (in addition to dynamic route param)
      { source: "/u/:id", destination: "/user/:id" }
    ];
  }
};

4

更新:正如nunorbatista所说:使用NextJS 10,你可以原生地实现此操作。你的next.config.js应该如下:

module.exports = {
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
}

旧答案:

文件夹结构是正确的,但是你不需要在 [language] 文件夹内编写重复的代码。只需从“main”文件夹导入页面即可。目前使用Next.js设置多语言还有些复杂。以下是目前的情况。

如果您想使用库

如果您要自己完成,您应该修改它们以符合您的需求。


谢谢。现在我这样做: import IndexPage, { getStaticProps, getStaticPaths } from '@/pages/index'; export { getStaticProps, getStaticPaths } ; export default IndexPage; - Markus Müller

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接