@mico_fe/i18n-core
v1.0.0
Published
Core i18n utilities - framework agnostic
Readme
@mico_fe/i18n-core
框架无关的国际化核心库
📦 安装
npm install @mico_fe/i18n-core
# 或
pnpm add @mico_fe/i18n-core
# 或
yarn add @mico_fe/i18n-core🎯 功能
- 🔄
t(key)- 按 key 翻译 - 📝
tt(text)- 按中文文案翻译 - ✅
te(key)/tte(text)- 检查翻译是否存在 - 🔧 可自定义参数替换
- 🌐 内置 30+ 语言名称和国旗映射
📖 API
createTranslator
创建翻译器实例:
import { createTranslator } from '@mico_fe/i18n-core'
const messages = {
'zh-CN': {
'button.submit': '提交',
'message.hello': '你好,{name}!',
},
'en-US': {
'button.submit': 'Submit',
'message.hello': 'Hello, {name}!',
},
}
let currentLang = 'zh-CN'
const translator = createTranslator(
{
messages,
availableLangs: ['zh-CN', 'en-US'],
defaultLang: 'zh-CN',
},
{ warnOnMissing: true },
() => currentLang,
(lang) => { currentLang = lang }
)
// 使用
translator.t('button.submit') // "提交"
translator.t('message.hello', { name: 'Vue' }) // "你好,Vue!"
translator.tt('提交') // "提交" (中文环境) / "Submit" (英文环境)
translator.te('button.submit') // true
translator.tte('提交') // truereplaceParams
参数替换函数,支持三种格式:
import { replaceParams } from '@mico_fe/i18n-core'
// {name} 格式
replaceParams('你好,{name}!', { name: 'Vue' }) // "你好,Vue!"
// %AA 格式
replaceParams('共 %count 条', { count: 100 }) // "共 100 条"
// $AA 格式
replaceParams('价格:$price 元', { price: 99 }) // "价格:99 元"语言映射
import { LANG_MAP, getLangName, getLangFlag, getLangInfo } from '@mico_fe/i18n-core'
getLangName('zh-CN') // "简体中文"
getLangFlag('zh-CN') // "🇨🇳"
getLangInfo('en-US') // { name: "English", flag: "🇺🇸" }
// 自定义语言映射
const customMap = {
'my-lang': { name: '自定义语言', flag: '🏳️' }
}
getLangName('my-lang', customMap) // "自定义语言"反向映射
从文案查找 key:
import { buildTextToKeyMap, findKeyByText } from '@mico_fe/i18n-core'
const messages = {
'button.submit': '提交',
'button.cancel': '取消',
}
const textToKeyMap = buildTextToKeyMap(messages)
findKeyByText('提交', textToKeyMap) // "button.submit"📝 类型定义
// 语言模块接口
interface LocaleModule {
messages: Record<string, Record<string, string>>
availableLangs: string[]
defaultLang?: string
langMap?: Record<string, LangInfo>
replaceParams?: (text: string, params: Record<string, any>) => string
}
// 语言信息
interface LangInfo {
name: string
flag: string
}
// 翻译选项
interface TranslateOptions {
params?: Record<string, any>
defaultValue?: string
}
// 配置
interface I18nCoreConfig {
fallbackLang?: string
warnOnMissing?: boolean
}📄 License
MIT
