国际化 (i18n)
使用 withConvert 方法实现单位的本地化显示。
基础用法
ts
import SmartUnit from 'smart-unit'
// 创建基础实例
const size = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
// 添加中文转换
const zhSize = size.withConvert((unit) => {
const map = {
ms: '毫秒',
s: '秒',
m: '分钟',
h: '小时',
}
return map[unit] || unit
})
console.log(zhSize.format(60 * 60 * 1000)) // => "1小时"与框架 i18n 集成
React + react-i18next
ts
import { useTranslation } from 'react-i18next'
import SmartUnit from 'smart-unit'
const baseUnit = new SmartUnit(['g', 1000, 'kg', 1000, 't'])
export const useWeightUnit = () => {
const { t } = useTranslation()
// 如果语言中没有对应的翻译,会抛出类型错误
return baseUnit.withConvert((unit) => t(`weight.${unit}`))
}完整示例: React CodeSandbox
Vue + vue-i18n
ts
import { useI18n } from 'vue-i18n'
import SmartUnit from 'smart-unit'
const baseUnit = new SmartUnit(['g', 1000, 'kg', 1000, 't'])
export const useWeightUnit = () => {
const { t } = useI18n()
return baseUnit.withConvert((unit) => t(`weight.${unit}`))
}完整示例: Vue CodeSandbox
链式格式化国际化
ts
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
// 中文版
const zhTime = time.withConvert((unit) => {
const map = { ms: '毫秒', s: '秒', m: '分钟', h: '小时' }
return map[unit] || unit
})
console.log(zhTime.formatChain(3661000, ' '))
// => "1小时 1分钟 1秒"关键点
withConvert 特性
withConvert 返回的新实例继承原实例的所有配置(如 fractionDigits、useDecimal),只是添加了单位转换函数。
翻译文本
翻译文本可以来自任何地方:硬编码、i18n 库、JSON 文件等。smart-unit 不依赖特定的 i18n 方案。