Internationalization (i18n)
Use the withConvert method to implement unit localization.
Basic Usage
ts
import SmartUnit from 'smart-unit'
// Create a base instance
const size = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
// Add Chinese translation
const zhSize = size.withConvert((unit) => {
const map = {
ms: '毫秒',
s: '秒',
m: '分钟',
h: '小时',
}
return map[unit] || unit
})
console.log(zhSize.format(60 * 60 * 1000)) // => "1 小时"Integration with Framework 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()
// If there's no corresponding translation in the language, a type error will be thrown
return baseUnit.withConvert((unit) => t(`weight.${unit}`))
}Full Example: 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}`))
}Full Example: Vue CodeSandbox
Chain Formatting with i18n
ts
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h'])
// Chinese version
const zhTime = time.withConvert((unit) => {
const map = { ms: '毫秒', s: '秒', m: '分钟', h: '小时' }
return map[unit] || unit
})
console.log(zhTime.formatChain(3661000, ' '))
// => "1 小时 1 分钟 1 秒"Key Points
withConvert Feature
withConvert returns a new instance that inherits all configurations from the original instance (such as fractionDigits, useDecimal), only adding the unit conversion function.
Translation Text
Translation text can come from anywhere: hardcoded strings, i18n libraries, JSON files, etc. smart-unit doesn't depend on a specific i18n solution.