答案:实现轻量级JavaScript国际化库,支持多语言管理、动态插值及日期数字货币格式化。1. 定义嵌套语言包,通过ResourceManager加载切换语言;2. 使用正则解析模板占位符,调用formatValue按类型格式化;3. I18n类整合资源与格式化逻辑,提供t方法翻译文本;4. 可扩展复数、ICU语法、异步加载等特性。

实现一个轻量级的 JavaScript 国际化(i18n)格式化库,核心是支持多语言文本管理、动态插值、日期/数字/货币格式化,并具备良好的扩展性。下面是一个实用且结构清晰的实现思路。
国际化库的基础是语言资源。将不同语言的翻译内容组织成嵌套对象,便于按模块或页面划分。
示例语言包:
{
"zh-CN": {
"greeting": "你好,{name}",
"count": "数量:{count, number}",
"date": "今天是:{today, date}",
"price": "价格:{amount, currency}"
},
"en-US": {
"greeting": "Hello, {name}",
"count": "Count: {count, number}",
"date": "Today is: {today, date}",
"price": "Price: {amount, currency}"
}
}创建一个 ResourceManager 来加载和切换语言包:
立即学习“Java免费学习笔记(深入)”;
class ResourceManager {
constructor(messages) {
this.messages = messages;
this.locale = 'en-US';
}
setLocale(locale) {
if (this.messages[locale]) {
this.locale = locale;
} else {
console.warn(`Locale ${locale} not found`);
}
}
getMessage(key) {
return this.messages[this.locale]?.[key] || key;
}
}解析占位符如 {name} 或带类型的 {value, number},并调用对应格式化器。
支持基本类型格式化:
格式化处理器:
function formatValue(value, type, locale) {
switch (type) {
case 'number':
return value.toLocaleString(locale);
case 'currency':
return value.toLocaleString(locale, { style: 'currency', currency: 'USD' });
case 'date':
return new Date(value).toLocaleDateString(locale);
default:
return String(value);
}
}解析模板字符串:
function interpolate(template, data, locale) {
return template.replace(/\{(\w+)(,\s*(\w+))?\}/g, (match, key, _, type) => {
const rawValue = data[key];
if (type) {
return formatValue(rawValue, type.trim(), locale);
}
return rawValue !== undefined ? rawValue : match;
});
}整合资源管理和格式化逻辑:
class I18n {
constructor(messages, options = {}) {
this.resourceManager = new ResourceManager(messages);
this.locale = options.locale || 'en-US';
this.resourceManager.setLocale(this.locale);
}
setLocale(locale) {
this.locale = locale;
this.resourceManager.setLocale(locale);
}
t(key, data = {}) {
const template = this.resourceManager.getMessage(key);
return interpolate(template, data, this.locale);
}
}使用方式:
const i18n = new I18n(messages, { locale: 'zh-CN' });
i18n.t('greeting', { name: '小明' });
// 输出:你好,小明
i18n.t('count', { count: 1000 });
// 输出:数量:1,000
i18n.setLocale('en-US');
i18n.t('greeting', { name: 'John' });
// 输出:Hello, John在基础版本上可逐步增强:
以上就是如何实现一个JavaScript的国际化(i18n)格式化库?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号