如何用 NextJS 和 next-i18next 翻译路由?
How to translate routes with NextJS and next-i18next?
我正在使用 next.JS 和软件包 next-i18next 构建一个多语言网站。它进展顺利,除了一件事我不确定什么是最好的方法。我希望我的静态路由也能被翻译(不仅仅是页面内容),例如:
示例。com/en/home -> 示例。com/pt-br/inicio
示例。com/en/contact -> 示例。com/pt-br/contato
我知道我可以创建目录 (en/pt-br) 并在其中插入页面(例如:home.js、contact.js 等在“/en/”和 inicio.js, contato.js etc inside "/pt-br/"), 这样当用户访问任何这些页面时很容易定义语言,但我需要创建 2 个文件几乎所有相同的内容(例如:“/en/home”和“/pt-br/inicio”)。所以我想知道是否有更好的解决方案?
谢谢!
对于解决方法,
我将组件页面创建为一个单独的模块,然后将其导入和导出到语言环境页面文件夹。所以我可以为多种语言重用 1 个组件。
您可以使用 Next.js rewrites.
,而不是为多种语言复制同一页面,这会损害构建性能并且如果您需要支持超过 5 种语言则无法扩展
它是在 v9.5
中引入的,它允许您重写特定页面的路径,在您的示例中,您可以为主要语言创建页面,并且可以添加所有辅助语言的重写支持.
结合 i18n subpaths(在 v10
中引入)next 将处理语言环境部分 (/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',
}
]
},
}
有关详细信息,请查看 Rewrites with i18n support 文章。
我正在使用 next.JS 和软件包 next-i18next 构建一个多语言网站。它进展顺利,除了一件事我不确定什么是最好的方法。我希望我的静态路由也能被翻译(不仅仅是页面内容),例如:
示例。com/en/home -> 示例。com/pt-br/inicio
示例。com/en/contact -> 示例。com/pt-br/contato
我知道我可以创建目录 (en/pt-br) 并在其中插入页面(例如:home.js、contact.js 等在“/en/”和 inicio.js, contato.js etc inside "/pt-br/"), 这样当用户访问任何这些页面时很容易定义语言,但我需要创建 2 个文件几乎所有相同的内容(例如:“/en/home”和“/pt-br/inicio”)。所以我想知道是否有更好的解决方案?
谢谢!
对于解决方法,
我将组件页面创建为一个单独的模块,然后将其导入和导出到语言环境页面文件夹。所以我可以为多种语言重用 1 个组件。
您可以使用 Next.js rewrites.
,而不是为多种语言复制同一页面,这会损害构建性能并且如果您需要支持超过 5 种语言则无法扩展它是在 v9.5
中引入的,它允许您重写特定页面的路径,在您的示例中,您可以为主要语言创建页面,并且可以添加所有辅助语言的重写支持.
结合 i18n subpaths(在 v10
中引入)next 将处理语言环境部分 (/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',
}
]
},
}
有关详细信息,请查看 Rewrites with i18n support 文章。