Paraglide JS

要从 typesafe-i18n 迁移到 Paraglide JS,只需将 src/i18n/{locale}/index.ts 中的字典导出为 messages/{locale}.json,转换少数用到复数形式、switch-case 或格式化器的消息,再把 LL.key() 调用替换为 m.key()。键、嵌套结构和 {name} 占位符均可原样沿用。

npx @inlang/paraglide-js init

为什么要迁移,以及什么情况下不该迁移:参见 Paraglide vs typesafe-i18n。

概述

typesafe-i18nParaglide JS
src/i18n/en/index.ts(基础语言区域,TypeScript)messages/en.json
src/i18n/de/index.tsmessages/de.json
src/i18n/en/settings/index.ts(命名空间)messages/en.json 中嵌套的 settings 对象
生成器(npx typesafe-i18n)生成 i18n-types.ts、i18n-util*.tsVite 插件或 paraglide-js compile 生成 src/paraglide/
.typesafe-i18n.jsonproject.inlang/settings.json
formatters.ts在消息中声明的格式化器(格式化)
检测器(navigatorDetector 等)语言区域策略

目前没有能读取 typesafe-i18n TypeScript 字典的 inlang 插件。虽然有一个 typesafe-i18n 的 inlang 插件,但它基于 2023 年的 inlang API(inlang.config.js),无法与当前版本的 Paraglide 配合使用。一次性转换为 JSON 更简单,而且翻译工具和 inlang CLI 处理的正是这些 JSON 文件。

1. 设置 Paraglide

在项目中运行 init。该命令会创建 project.inlang/settings.json (已配置 inlang 消息格式插件) 、messages/ 文件夹,以及 Vite 插件或编译脚本:

npx @inlang/paraglide-js init

在 project.inlang/settings.json 中设置与你的 typesafe-i18n 项目相同的基础语言区域和语言区域:

{
  "baseLocale": "en",
  "locales": ["en", "de", "fr"]
}

其余设置请参考对应框架的指南:SvelteKit、React + Vite、Astro、Vite 或 Vanilla JS/TS。

2. 将字典导出为 JSON

typesafe-i18n 的字典是带默认导出的 TypeScript 模块,因此只需一个简短的脚本即可导入它们并输出为 JSON。将以下脚本保存为 scripts/export-typesafe-i18n.mts:

// 将 src/i18n/<locale>/ 中的 typesafe-i18n 字典转换为 messages/<locale>.json
import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";

const i18nDir = "src/i18n";
const needsManualConversion = new Map<string, Set<string>>();
const flag = (key: string, reason: string) =>
  needsManualConversion.set(key, (needsManualConversion.get(key) ?? new Set()).add(reason));

function convert(value: unknown, key: string): unknown {
  if (typeof value === "string") {
    // {name}, {name:string}, {name?}, {name?:string}, {0:number} -> {name} / {0}
    const converted = value.replace(
      /\{\s*(\w+)\s*(\?)?\s*(?::\s*\w+\s*)?\}/g,
      (_, name: string, optional?: string) => {
        if (optional) flag(key, `optional argument {${name}?}`);
        return `{${name}}`;
      },
    );
    const plurals = /\{\{[^{}]*\}\}/g;
    const switchCases = /\{[^{}]*\|\s*\{[^{}]*\}\s*\}/g;
    const rest = converted.replace(plurals, "").replace(switchCases, "");
    if (plurals.test(converted)) flag(key, "plural {{…}}");
    if (switchCases.test(converted)) flag(key, "switch-case {x|{…}}");
    if (/\{[^{}]*\|/.test(rest)) flag(key, "formatter {x|…}");
    if (/\{[^{}|]*:[^{}|]*\}/.test(rest)) flag(key, "argument type that isn't one word");
    if (/\{\s*\d+\s*\}/.test(converted)) flag(key, "index argument {0}");
    return converted;
  }
  if (Array.isArray(value)) {
    flag(key, "array");
    return value;
  }
  return Object.fromEntries(
    Object.entries(value as Record<string, unknown>).map(([k, v]) => [
      k,
      convert(v, key ? `${key}.${k}` : k),
    ]),
  );
}

async function load(dir: string) {
  const file = resolve(dir, "index.ts");
  return existsSync(file) ? (await import(pathToFileURL(file).href)).default : {};
}

mkdirSync("messages", { recursive: true });
for (const locale of readdirSync(i18nDir, { withFileTypes: true })) {
  if (!locale.isDirectory()) continue;
  const dir = join(i18nDir, locale.name);
  const dictionary = { ...(await load(dir)) };
  // 命名空间:src/i18n/<locale>/<namespace>/index.ts -> "<namespace>.<key>"
  for (const ns of readdirSync(dir, { withFileTypes: true })) {
    if (ns.isDirectory()) dictionary[ns.name] = await load(join(dir, ns.name));
  }
  const json = JSON.stringify(convert(dictionary, ""), null, 2);
  writeFileSync(join("messages", `${locale.name}.json`), json + "\n");
}
for (const [key, reasons] of needsManualConversion) {
  console.log(`Convert by hand: ${key} (${[...reasons].join(", ")})`);
}

在项目根目录下运行:

npx tsx scripts/export-typesafe-i18n.mts

它会覆盖 messages/{locale}.json,保留原有的嵌套结构,去除参数类型 ({name:string} → {name}) ,并列出所有需要在下一步手动转换的消息及原因。例如:

// src/i18n/en/index.ts
const en = {
  HI: "Hello {name:string}!",
  auth: { login: "Click here to log in" },
  apples: "{nrOfApples:number} {{apple|apples}}",
} satisfies BaseTranslation;

变为

{
  "HI": "Hello {name}!",
  "auth": { "login": "Click here to log in" },
  "apples": "{nrOfApples} {{apple|apples}}"
}

脚本随即输出 Convert by hand: apples (plural {{…}})。

3. 映射消息语法

纯文本和 {name} 参数无需修改。编译前,请按下面的模式逐条转换列出的消息;消息格式插件无法识别 typesafe-i18n 的 {{…}} 和 {x|…} 语法。

嵌套键

直接保留即可。消息格式插件会用点号把嵌套对象展平,生成的函数则通过方括号语法调用:

// typesafe-i18n
LL.auth.login();

// Paraglide
m["auth.login"]();

新消息为什么最适合用扁平键,请参阅消息键。不含点的键 (如 HI) 仍是普通属性:m.HI()。

索引参数

Paraglide 使用具名参数。请重命名 {0}、{1} (带类型的也一样,例如 {0:number}) ,并同步更新调用代码:

- "apples": "{0} apples"
+ "apples": "{count} apples"
LL.apples(12); // typesafe-i18n
m.apples({ count: 12 }); // Paraglide

可选参数

对于省略的可选参数({name?} 或 {name?:string}),typesafe-i18n 不会渲染任何内容。而 Paraglide 的参数始终是必填的,缺失的参数会渲染为 undefined。脚本会把 {name?:string} 转换为 {name} 并列出该消息,因此请逐一审阅每处调用:

  • 如果值可以为空,就传入空字符串:m.greeting({ name: user.name ?? "" })。开启 strict 后,TypeScript 会对所有可能传入 undefined 的调用报错。
  • 如果周围的文本也应一并去掉,就拆成两条消息,例如 greeting("Hello {name}!")和 greeting_anonymous("Hello!"),并在代码中选择使用哪一条。

复数形式

{{singular|plural}} 会转换为复数变体。两个库都使用 Intl.PluralRules:

{
  "apples": [
    {
      "declarations": ["input nrOfApples", "local nrOfApplesPlural = nrOfApples: plural"],
      "selectors": ["nrOfApplesPlural"],
      "match": {
        "nrOfApplesPlural=one": "{nrOfApples} apple",
        "nrOfApplesPlural=other": "{nrOfApples} apples"
      }
    }
  ]
}

简写形式的映射方式相同:apple{{s}} 对应 one → apple、other → apples;?? items 对应 {nrOfApples} items;完整形式 {{zero|one|two|few|many|other}} 则会为该语言区域用到的每个类别各生成一个变体。注意,typesafe-i18n 始终把 0 视为 zero,而在英语中,Intl.PluralRules 对 0 返回的是 other。因此,如果你的消息对零有单独的文本,需要添加一个精确的 0 匹配:

{
  "list_items": [
    {
      "declarations": [
        "input count",
        "local countExact = count",
        "local countPlural = count: plural"
      ],
      "selectors": ["countExact", "countPlural"],
      "match": {
        "countExact=0, countPlural=*": "The list includes no items",
        "countExact=*, countPlural=one": "The list includes an item",
        "countExact=*, countPlural=*": "The list includes {count} items"
      }
    }
  ]
}

Switch-case

{gender|{male: his, female: her, *: their}} 会变成基于 gender 输入的变体。每个变体中都写完整的句子,这样译者看到的也是完整的句子:

{
  "photo_added": [
    {
      "declarations": ["input username", "input gender"],
      "selectors": ["gender"],
      "match": {
        "gender=male": "{username} added a new photo to his stream.",
        "gender=female": "{username} added a new photo to her stream.",
        "gender=*": "{username} added a new photo to their stream."
      }
    }
  ]
}

格式化器

Paraglide 内置了 number、datetime 和 relativetime 格式化器,会把选项直接传给 Intl。typesafe-i18n 中的 weekday 格式化器可改写为:

{
  "today": [
    {
      "declarations": ["input date", "local weekday = date: datetime weekday=long"],
      "match": { "date=*": "Today is {weekday}" }
    }
  ]
}

uppercase 等自定义格式化器没有对应的写法;请在代码中自行处理,作用于消息的输出或你传入的参数。

数组

数组(LL[0]())没有直接对应的写法。可以为每个条目分配一个键,或按照对象和数组中的说明存储为 JSON 字符串。

4. 替换调用点

typesafe-i18nParaglide JS
import LL from "./i18n/i18n-svelte"import { m } from "$lib/paraglide/messages.js"
const { LL } = useI18nContext()import { m } from "./paraglide/messages.js" (无需 hook 或提供商)
$LL.HI({ name }) / LL.HI({ name })m.HI({ name })
LL.auth.login()m["auth.login"]()
get(LL).HI() (组件外部)m.HI()
setLocale("de")来自 paraglide/runtime.js 的 setLocale("de") (会重新加载或跳转页面)
适配器提供的 $locale / localegetLocale()
loadLocaleAsync(locale)、loadNamespaceAsync(locale, ns)删除;消息在使用处直接导入
带检测器的 detectLocale(...)strategy 选项,例如 ["url", "cookie", "preferredLanguage", "baseLocale"] (策略)
<TypesafeI18n locale={locale}>删除该提供商
使用临时字符串的 i18nString / LLL("…")将该字符串添加为一条消息

大多数 LL 调用都能用一条 Perl 命令改写。它会把 $LL.HI( 改成 m.HI(,把 LL.auth.login( 改成 m['auth.login'](,跳过 src/i18n,其余内容不做改动。请先提交,再审阅 diff:

find src \( -name '*.svelte' -o -name '*.ts' -o -name '*.tsx' -o -name '*.vue' \) -not -path 'src/i18n/*' -print0 | xargs -0 perl -pi -e 's{(?<![\w.$])\$?LL((?:\.\w+)+)\(}{my $k = substr($1, 1); $k =~ /\./ ? "m[\x27$k\x27](" : "m.$k("}ge'

然后在每个改动过的文件中添加 m 的导入,并手动处理该命令匹配不到的情况:get(LL)、LL[0] 这类数组访问,以及被当作值传递的 LL。如果你在第 3 步中重命名了索引参数,也要同步更新这些调用;tsc 或 svelte-check 会报告所有参数不再匹配的调用。

5. 增量迁移(可选)

你不必一次性切换所有组件。typesafe-i18n 会继续读取 src/i18n/,同时 Paraglide 编译 messages/,因此两者可以并行运行:

  • 新消息只写入 messages/{locale}.json。
  • 逐个将组件迁移到 m.*;某条消息不再被调用后,就将其从 typesafe-i18n 字典中删除。
  • 避免在两处同时编辑同一条消息;在旧字典移除之前,译者应以 JSON 文件为准进行翻译。

增量迁移指南更详细地介绍了并行运行的配置方式。注意,两个库会各自跟踪语言区域;如果使用 Paraglide 的 cookie 或 URL 策略,请用 getLocale() 的返回值设置 typesafe-i18n 的语言区域,确保两者一致。

6. 移除 typesafe-i18n

当代码中不再有任何 LL 调用时:

  1. 删除 src/i18n/(字典和生成的 i18n-*.ts 文件)、.typesafe-i18n.json 和 scripts/export-typesafe-i18n.mts。
  2. 从 package.json 中移除 typesafe-i18n 脚本,并卸载该包:npm uninstall typesafe-i18n。
  3. 运行类型检查和测试。

7. 使用 General Translation 翻译缺失的语言区域

typesafe-i18n 将翻译工作留给你自己完成,或交给你通过其导入器和导出器包接入的服务。Paraglide 的消息文件可配合 inlang CLI 使用,它会补全所有缺失的翻译,并在源消息变更时同步更新相应译文。我们推荐 General Translation,也就是维护 Paraglide JS 的公司:

npx @inlang/cli machine translate --project ./project.inlang

首次运行时会询问要使用哪个提供商;选择 General Translation,并在浏览器中登录。复数形式会生成目标语言所需的全部复数形式,占位符也会原样保留。先以 diff 形式审阅结果,再运行检查:

npx @inlang/cli check --project ./project.inlang

翻译消息介绍了 CI、编码代理以及其他服务提供方。

后续步骤

  • 变体 — 复数形式、精确匹配和 select 选择
  • 格式化 — 数字、日期和相对时间
  • 标记 — 在消息中使用链接和强调(typesafe-i18n 不支持此功能)
  • 检查翻译 — 出现缺失的翻译或未使用的消息时让 CI 失败