
本文介绍如何基于 svelte-i18n 的 format 可读 Store,创建支持路径前缀(如 section.subSection)的可链式调用翻译函数,并保持 $ 解包语法兼容性,实现 {$s('.value')} 或 {$s('value')} 的简洁用法。
本文介绍如何基于 `svelte-i18n` 的 `format` 可读 store,创建支持路径前缀(如 `section.subsection`)的可链式调用翻译函数,并保持 `$` 解包语法兼容性,实现 `{$s('.value')}` 或 `{$s('value')}` 的简洁用法。
在 Svelte 应用中,svelte-i18n 提供了响应式的国际化能力,其核心导出 format 是一个 可读 Store(readable store),它会随语言切换自动更新翻译函数。若需为组件或模块定义局部翻译上下文(例如统一前缀 auth.login),直接拼接字符串易出错、难复用,且无法享受 $ 语法糖带来的响应式解包能力。
正确做法是:将 format 作为源 Store,使用 derived 创建一个新的可读 Store,其值是一个闭包翻译函数。该函数接收相对键(如 '.submit' 或 'submit'),自动补全基础路径,并委托给底层 $format 执行实际翻译。
以下是推荐实现(保存为 lib/i18n/section.js):
import { derived } from 'svelte/store';
import { format } from 'svelte-i18n';
export function section(path) {
const { subscribe } = derived(
format,
($format) => (idOrMessage, options = {}) => {
// 支持相对路径:以 '.' 开头时自动拼接 base path
if (typeof idOrMessage === 'string') {
const key = idOrMessage.startsWith('.')
? `${path}${idOrMessage}`
: idOrMessage;
return $format(key, options);
}
// 支持对象形式消息(含 id 字段)
return $format(
{
...idOrMessage,
id: `${path}.${idOrMessage.id}`
},
options
);
}
);
return {
path,
subscribe,
// 支持链式构造子上下文(如 section('a').section('b') → 'a.b')
section: (subPath) => section(`${path}.${subPath}`)
};
}
✅ 使用示例(.svelte 组件中):
<script>
import { section } from '$lib/i18n/section.js';
// 创建根上下文
const auth = section('auth');
// 创建嵌套上下文(等价于 section('auth.login'))
const login = auth.section('login');
// 也可一步到位
const signup = section('auth.signup');
</script><!-- 所有写法均响应式,支持 $ 解包 --><p>{$auth('.title')}</p> <!-- → $format('auth.title') -->
<p>{$login('submit')}</p> <!-- → $format('auth.login.submit') -->
<p>{$signup('.error.required')}</p> <!-- → $format('auth.signup.error.required') -->
⚠️ 关键注意事项:
- 必须返回含 subscribe 方法的对象:Svelte 的 $ 语法仅识别符合 Store 接口(即具有 subscribe 函数)的对象,直接返回普通函数(如 (key) => ...)无法被 $ 解包;
- 避免手动 subscribe() 调用:原问题中在闭包内调用 _.subscribe() 并试图同步返回值,会导致竞态、首次渲染为空等问题;derived 自动处理响应式依赖与更新;
- 路径拼接逻辑应内聚:推荐仅在 derived 内部处理 . 前缀解析,外部调用者无需关心分隔符——这提升了 API 的健壮性与可读性;
- 链式 section() 支持模块化组织:大型应用中可按功能域(user, payment, settings)拆分上下文,复用性高且无命名冲突风险。
通过此模式,你既保留了 svelte-i18n 的全部能力(如插值、复数、富文本),又获得了语义清晰、可组合、可测试的本地化上下文封装,真正实现“一次定义,处处 $”。










