Paraglide JS 可以通过 inlang 插件编译任意格式的翻译文件。也就是说,你可以让 Paraglide 与现有的 i18n 库并行运行,两者读取同一套翻译文件。
为什么选择 Paraglide JS?
- 类型安全 — 消息键和参数自动补全,拼写错误在编译时即可发现
- 更小的包体积 — 通过 Tree-shaking 移除未使用的翻译,i18n 包体积最多可减小 70%
- 更好的开发体验 — IDE 能识别每个消息键及其参数
工作原理
- 无需迁移翻译文件 — Paraglide 直接读取你现有的 i18next、react-intl 或自定义 JSON 文件
- 两个库并行运行 — 新代码用 Paraglide,现有代码照常运行
- 渐进式采用 — 按自己的节奏迁移组件,也可以长期同时保留两者
- 同一个事实来源 — 两个库读取同一套翻译文件
[!NOTE]本示例使用 i18next 翻译文件,但只要某种格式有对应的 inlang 插件,同样的方法就适用。
配置
1. 安装 Paraglide JS
npx @inlang/paraglide-js@latest init
2. 为你的翻译格式添加插件
Paraglide 通过 inlang 插件读取翻译文件。在 project.inlang/settings.json 中添加与你现有格式对应的插件:
{
"baseLocale": "en",
"locales": ["en", "de", "fr"],
"modules": [
- "https://cdn.jsdelivr.net/npm/@inlang/message-format-plugin@latest/dist/index.js"
+ "https://cdn.jsdelivr.net/npm/@inlang/plugin-i18next@6.4.0/dist/index.js"
],
+ "plugin.inlang.i18next": {
+ "pathPattern": "./locales/{locale}.json"
+ }
}
现在,Paraglide 会将你现有的 i18next 翻译文件编译为类型化的消息函数。
3. 同时使用两个库
两个库读取的是同一套翻译文件:
import i18next from 'i18next';
import { m } from './paraglide/messages.js';
// 同一条翻译,两种访问方式
i18next.t('greeting', { name: 'World' }); // i18next(运行时)
m.greeting({ name: 'World' }); // Paraglide(编译时,类型安全)
新代码使用 Paraglide,现有的 i18next 代码无需修改,照常运行。
延伸阅读
- 翻译文件格式 — 所有支持的格式和插件
- 与 i18next 的对比 — 逐项功能对比
- Why I Replaced i18next with Paraglide JS — 一位开发者的亲身经历
