前言
有关 Next.js 国际化的方案网上很多,而且各部相同,但大部分的方案都是在 /app
目录下添加动态路由 [lang]
这样的形式,这不是我想要的效果。
我希望国际化的实现不能破坏应用程序的目录结构和路由,在经过一段时间摸索后,发现 next-intl
有提供现成的方案:
更多详细文档:next-intl
如果官方文档打不开的伙伴,可以到 Github 上克隆代码,本地运行根目录的
docs
文件夹
具体步骤
- 安装依赖
pnpm add next-intl
- 根目录新建
messages
文件夹,并写入对应的国际化文件:
// en.json
{
"Route":{
"about":"About",
"dashboard":"Dashboard",
"system-manage":"System Manage",
"internationalization":"Internationalization"
}
}
// zh.json
{
"Route":{
"about":"关于",
"dashboard":"仪表盘",
"system-manage":"系统管理",
"internationalization":"国际化"
}
}
- 根目录的
next.config.ts
文件设置插件:
import type {
NextConfig } from "next";
import createNextIntlPlugin from 'next-intl/plugin';