要从 svelte-i18n 迁移到 Paraglide JS,只需让 Paraglide 的 ICU MessageFormat 插件指向现有的语言区域 JSON 文件,将嵌套的键一次性扁平化,再把 $_("key", { values }) 替换为 m["key"](values)。你的 ICU 消息 (包括复数形式和 select) 无需改动即可直接编译;在最后一个调用点移除之前,svelte-i18n 仍可照常读取同一批文件。
npx @inlang/paraglide-js init
为什么要迁移,以及什么情况下不该迁移:请参阅 Paraglide 与 svelte-i18n 对比。
概览
| svelte-i18n | Paraglide JS |
|---|---|
src/lib/i18n/locales/en.json(ICU MessageFormat) | 同一文件,由 ICU MessageFormat 插件读取 |
register("de", () => import("./locales/de.json")) | project.inlang/settings.json 中的 "locales": ["en", "de"] |
init({ fallbackLocale, initialLocale }) | baseLocale 和语言区域策略 |
$_("key", { values }) | m["key"](values) |
$locale、locale.set() | getLocale()、setLocale() |
hooks.server.ts 根据 Accept-Language 设置 locale | hooks.server.ts 中的 paraglideMiddleware |
+layout.ts 中的 waitLocale() | 直接删除;消息会在使用处随应用打包 |
示例沿用 svelte-i18n 的 SvelteKit 指南中的 src/lib/i18n/locales/ 目录;请按你的文件实际位置调整路径。
1. 设置 Paraglide
先运行 init,然后按照 SvelteKit 指南 (若是不使用 SvelteKit 的 Svelte 应用,请参阅 Vite 指南) 配置 Vite 插件和 hooks.server.ts:
npx @inlang/paraglide-js init
2. 使用 ICU 插件读取 ICU JSON
svelte-i18n 的消息采用 ICU MessageFormat 格式。在 project.inlang/settings.json 中将消息格式插件替换为 ICU 插件,并将其指向你的文件:
{
"baseLocale": "en",
"locales": ["en", "de"],
"modules": ["https://cdn.jsdelivr.net/npm/@inlang/plugin-icu1@1.3.11/dist/index.js"],
"plugin.inlang.icu-messageformat-1": {
"pathPattern": "./src/lib/i18n/locales/{locale}.json"
}
}
语言区域代码请与文件名保持一致。如果 svelte-i18n 曾通过回退机制将 en-US 解析为 en.json,请在此处填写 en,再由策略将浏览器语言匹配到该语言区域。
将嵌套键扁平化
ICU 插件只读取顶层的字符串值,会跳过嵌套对象。因此,像下面这样的嵌套文件只会编译 title:
{
"title": "Sign up",
"field": { "name": "Name", "birth": "Date of birth" }
}
用点分隔的键把文件一次性扁平化。svelte-i18n 读取点分隔键的方式与读取嵌套键相同,因此 $_("field.name") 照常可用。
先检查 $json 调用。 扁平化会移除父对象:扁平化之后,$json("field") 会返回 undefined。$_ 调用,以及通过完整键读取字符串或数组的 $json 调用 (如 $json("list.items")) 不受影响。用 grep -rnF '$json(' src 找出这些调用。如果其中有读取对象的调用,可以先让相关组件弃用 $json,也可以为 Paraglide 单独生成一份扁平化文件,让 svelte-i18n 继续使用原始文件 (见下文) 。
将以下内容保存为 scripts/flatten-messages.mjs:
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
// node scripts/flatten-messages.mjs <dir> [outDir] (outDir 默认为 dir,即原地覆盖)
const [dir, outDir = dir] = process.argv.slice(2);
mkdirSync(outDir, { recursive: true });
const flatten = (object, prefix = "") =>
Object.entries(object).flatMap(([key, value]) =>
value && typeof value === "object" && !Array.isArray(value)
? flatten(value, `${prefix}${key}.`)
: [[`${prefix}${key}`, value]],
);
for (const file of readdirSync(dir).filter((name) => name.endsWith(".json"))) {
const messages = Object.fromEntries(flatten(JSON.parse(readFileSync(join(dir, file), "utf8"))));
writeFileSync(join(outDir, file), JSON.stringify(messages, null, 2) + "\n");
}
node scripts/flatten-messages.mjs src/lib/i18n/locales
{
"title": "Sign up",
"field.name": "Name",
"field.birth": "Date of birth"
}
数组 (通过 $json 读取) 会保持原样,不会被编译;详见对象和数组。
如果组件仍通过 $json 读取对象,请改为将扁平化后的副本写入另一个文件夹,并将 pathPattern 指向这些文件 (./src/lib/i18n/flat/{locale}.json) :
node scripts/flatten-messages.mjs src/lib/i18n/locales src/lib/i18n/flat
这些副本是生成出来的:请继续编辑原始文件,编译前重新运行脚本;在原地完成扁平化之前,不要运行 machine translate,因为它会写入 Paraglide 读取的文件。
哪些可以直接沿用
ICU 插件会把 svelte-i18n 的消息语法编译为相同的输出:
| ICU 消息 | 调用 |
|---|---|
"{name} is awesome!" | m.awesome({ name }) |
"You have {count, plural, =0 {no items} one {# item} other {# items}}" | m["cart.items"]({ count }) |
"{gender, select, male {He} female {She} other {They}} liked this" | m.liked({ gender }) |
"{place, selectordinal, one {#st} two {#nd} few {#rd} other {#th}}" | m.rank({ place }) |
"{n, number}", "{d, date, short}", "{t, time, short}" | 使用 Intl 按当前语言区域格式化 |
有两点需要注意:
- 自定义命名格式和骨架(skeleton)。 Paraglide 无法识别通过
init({ formats })定义的格式,例如{price, number, EUR}。骨架也会被忽略:::currency/EUR会格式化为普通数字,::yyyyMMdd、::HHmm等日期和时间骨架则会回退为medium样式。请在代码中用Intl.NumberFormat或Intl.DateTimeFormat格式化这些值,再将结果传入(例如new Intl.NumberFormat(getLocale(), { style: "currency", currency: "EUR" }).format(price)),或改用标准样式,如{share, number, percent}、{d, date, short}或{t, time, short}。 - 消息中的 HTML 仍可通过
{@html m.key()}使用。ICU 插件会把标签当作纯文本处理;如需带类型检查的链接和强调样式,请使用 Paraglide 的标记,但这需要使用 inlang 消息格式。
3. 替换调用点
| svelte-i18n | Paraglide JS |
|---|---|
import { _ } from "svelte-i18n" | import { m } from "$lib/paraglide/messages.js" |
$_("title")、$t("title")、$format("title") | m.title() |
$_("field.name") | m["field.name"]() |
$_("awesome", { values: { name } }) | m.awesome({ name }) |
$_("title", { locale: "de" }) | m.title({}, { locale: "de" }) |
$_("title", { default: "Sign up" }) | m.title() (键会经过类型检查;缺失的翻译会回退到基础语言区域) |
.ts 文件中的 get(_)("title") | m.title() |
$locale | $lib/paraglide/runtime.js 中的 getLocale() |
locale.set("de") | setLocale("de") (会触发导航或重新加载) |
$locales | $lib/paraglide/runtime.js 中的 locales |
$isLoading、waitLocale() | 直接删除 |
$number(n) | new Intl.NumberFormat(getLocale()).format(n),或在消息内部格式化 |
$date(d) | new Intl.DateTimeFormat(getLocale(), { dateStyle: "short" }).format(d) |
$time(d) | new Intl.DateTimeFormat(getLocale(), { timeStyle: "short" }).format(d) |
$json("list.items") | 参见对象和数组 |
在运行时调用 addMessages(locale, dict) | 无对应写法;消息在编译时生成 |
下面的 Perl 命令会重写使用字面量键、且不带选项或仅带 { values: { … } } 的 $_、$t 和 $format 调用:把 $_("title") 转换为 m.title(),把 $_("field.name") 转换为 m['field.name'](),把 $_("awesome", { values: { name } }) 转换为 m.awesome({ name })。带有其他选项或嵌套花括号的调用不会被改动。请先提交,再审阅 diff:
find src \( -name '*.svelte' -o -name '*.ts' -o -name '*.js' \) -not -path 'src/lib/paraglide/*' -print0 | xargs -0 perl -pi -e 's{\$(?:_|t|format)\(\s*([\x27"])([^\x27"]+)\1\s*(?:,\s*\{\s*values:\s*(\{[^{}]*\})\s*\}\s*)?\)}{my ($k, $v) = ($2, $3 // ""); ($k =~ /^[A-Za-z_]\w*$/ ? "m.$k" : "m[\x27$k\x27]") . "($v)"}ge'
然后在每个改动过的文件中添加 import { m } from "$lib/paraglide/messages.js",再搜索剩余需要替换的地方:
grep -rnE '\$(_|t|format|json|date|time|number)\(' src
这样,svelte-check 就会报告所有不存在的键和缺失的参数。
4. 增量迁移(可选)
由于两个库读取的是同一批扁平化文件,你可以逐个组件迁移:
-
保留 svelte-i18n 的
register()和init(),直到最后一个$_调用被移除。 -
新消息直接添加到同一批 JSON 文件中,两个库都能读取到。
-
在每个请求或页面加载开始的位置,用 Paraglide 的语言区域设置 svelte-i18n 的
localestore,使两者的语言区域保持同步。不要放在模块级的init()中,因为它只运行一次:// src/routes/+layout.ts(浏览器端) import { browser } from "$app/environment"; import { locale as svelteI18nLocale, waitLocale } from "svelte-i18n"; import { getLocale } from "$lib/paraglide/runtime.js"; export const load = async () => { // 在加载通过 register() 注册的字典时,set() 会返回一个 promise if (browser) await svelteI18nLocale.set(getLocale()); await waitLocale(); };// src/hooks.server.ts(服务端):SvelteKit 指南中的 hook,外加一行 await 语句 import type { Handle } from "@sveltejs/kit"; import { locale as svelteI18nLocale } from "svelte-i18n"; import { paraglideMiddleware } from "$lib/paraglide/server.js"; import { getTextDirection } from "$lib/paraglide/runtime.js"; export const handle: Handle = ({ event, resolve }) => paraglideMiddleware(event.request, async ({ request, locale }) => { await svelteI18nLocale.set(locale); // 为迁移而添加 return resolve( { ...event, request }, { transformPageChunk: ({ html }) => html.replace("%lang%", locale).replace("%dir%", getTextDirection(locale)), }, ); });在服务端,svelte-i18n 的
localestore 仍是所有请求共享的单一值,因此不同语言的并发请求可能会用错误的语言渲染剩余的$_调用,这一点与迁移前相同。已迁移到m.*的调用则是请求级作用域的。最后一个$_调用移除后,这一限制也就不复存在。
通用模式请参阅增量迁移。
5. 移除 svelte-i18n
当代码中不再有任何 svelte-i18n 调用时:
- 删除
src/lib/i18n/index.ts(即register()/init()的初始化配置),同时删除+layout.ts中对它的导入以及waitLocale()。 - 从
hooks.server.ts中移除 svelte-i18n 的语言区域处理逻辑,改由paraglideMiddleware接管。 - 卸载该包:
npm uninstall svelte-i18n。
ICU JSON 文件和 ICU 插件可以一直保留。之后是否切换到 inlang 消息格式 可自行决定;切换后可以使用标记和面向译者的描述。
6. 使用 General Translation 翻译缺失的语言区域
inlang CLI 通过 ICU 插件补全语言区域文件中所有缺失的翻译,并在源消息变更时同步更新对应的翻译。我们推荐使用 Paraglide JS 的维护方 General Translation:
npx @inlang/cli machine translate --project ./project.inlang
首次运行时会询问要使用哪个提供商;选择 General Translation,然后在浏览器中登录。占位符会原样保留,复数形式会按目标语言的需要生成所有变体。插件会以规范的 ICU 格式写回文件,因此首次运行后会出现一些空白字符的改动,属正常现象。审阅 diff 后,再检查结果:
npx @inlang/cli check --project ./project.inlang
翻译消息一文介绍了 CI、编码代理以及其他服务提供方。
后续步骤
- SvelteKit 指南 — 路由、SSR 和预渲染
- 国际化路由 — 本地化 URL,svelte-i18n 并未提供此功能
- 检查翻译 — 存在缺失的翻译或未使用的消息时,让 CI 检查失败
