本文介绍如何基于 svelte-i18n 的 format 可读存储(readable store),通过 derived 创建自定义翻译函数,使其既保留 $ 解包语法,又支持模块化、链式调用的相对路径键名(如 $('.value')),同时确保响应式更新。
本文介绍如何基于 `svelte-i18n` 的 `format` 可读存储(readable store),通过 `derived` 创建自定义翻译函数,使其既保留 `$` 解包语法,又支持模块化、链式调用的相对路径键名(如 `$('.value')`),同时确保响应式更新。
在 Svelte 应用中,svelte-i18n 提供了 $_(即 format store)作为核心翻译函数,它本身是一个
可读存储(readable store)
,其值为一个接受 (key, options) 的翻译函数。要实现类似 const _ = tr('base.path') 并允许后续使用 $_('.relative_key') 的语法,关键在于:
返回一个符合 Svelte store 协议的对象(含 subscribe 方法),而非普通函数
——这样它才能被 $ 自动解包并响应语言变更。
以下是推荐的封装方案(section.js):
✅
使用方式(组件内):
?
核心原理说明:
derived(format, fn) 创建了一个新的可读 store,其值是动态生成的翻译函数;
每当 format 更新(如切换语言、加载新词典),derived 会重新执行 fn,从而生成
最新上下文下的翻译函数
;
返回对象含 subscribe 方法,因此可被 $ 运算符识别并自动订阅,实现响应式更新;
section().section() 链式调用返回新 store,天然支持嵌套作用域,避免硬编码重复路径。
⚠️
注意事项:
不要在 section 内部手动调用 .subscribe() 或缓存返回值(如原问题中的 returnVal),这会破坏响应式链路;
路径拼接逻辑应统一在 derived 的回调中处理,避免在调用侧重复拼接(如不建议 tr('base')('.key'));
若需支持 t(带插值的翻译函数)或 formatMessage 等高级能力,可在 derived 回调中一并封装;
section 返回的是 store,
不可解构赋值为普通函数
(如 const { subscribe } = section(...) 后再单独用 subscribe),必须用 $ 解包。
通过该模式,你既能复用 svelte-i18n 的完整能力,又能构建清晰、可复用、可组合的本地化作用域,让多语言代码更贴近业务语义,也更易于维护。
// src/lib/section.js
import { derived } from 'svelte/store';
import { format } from 'svelte-i18n';
export function section(path) {
// 基于 format store 衍生出新的 store
const { subscribe } = derived(
format,
($format) => (idOrMessage, options = {}) => {
if (typeof idOrMessage === 'string') {
// 处理相对路径:'.key' → `${path}.key`
const key = idOrMessage.startsWith('.')
? `${path}${idOrMessage}`
: idOrMessage;
return $format(key, options);
}
// 支持 message 对象(含 id 字段)
return $format(
{
...idOrMessage,
id: `${path}.${idOrMessage.id}`
},
options
);
}
);
return {
subscribe,
path,
// 支持链式嵌套:s.section('sub').section('deep')
section: (subPath) => section(`${path}.${subPath}`)
};
}
{$user('name')}
{$profile('title')}
{$_('user.profile.description')}
{$profile('.bio')}
