Nextjs 14+ 国际化

803 阅读2分钟

在 Next.js 的官方示例仓库中展示了三种国际化的库 next-i18nextnext-translatenext-intl,当然还有不少开发者推荐的 react-i18next

根据下载量来说,目前 react-i18next 是 Next.js 中实现 i18n 最受欢迎的方案。

毫无疑问,我会直接选择 react-i18next 作为最终方案,其原因可想而知

  • 有一个活跃的社区和庞大的用户群体,提供了广泛的文档、示例和第三方插件
  • 基于i18next库,可提供强大的格式化功能,复数形式、日期和时间格式化等

当然缺点也很明显,因为它依赖于 i18next 的库,所以会增加 app 的包大小

开发环境配置

配置翻译文件类型约束

在开发时由于 key 值往往比较长,在使用时仍然需要在组件和翻译内容中切换,因此我们可以通过配置翻译文件的类型约束以实现代码提示。新增 types/i18next.d.ts 文件,写入以下内容:

import 'i18next';

import common from '../i18n/locales/en/common.json';
import home from '../i18n/locales/en/home.json';
import news from '../i18n/locales/en/news.json';

interface I18nNamespaces {
  home: typeof home;
  news: typeof news;
  common: typeof common;
}

declare module 'i18next' {
  interface CustomTypeOptions {
    defaultNS: 'common';
    resources: I18nNamespaces;
  }
}

这个全局类型声明文件中,我们将 api 及 common 模块的翻译文件引入,并通过 typeof 的方式将 json 文件转换为 ts 类型。

在配置声明文件后,后续配合 react-i18next 会获取到完整的代码提示,并且如果使用错误的 key 值时会直接报错,能够有效防止在页面中渲染错误的翻译内容。

方案详细设计

传送门