UNPKG

2.69 kBJavaScriptView Raw
1import { localeId } from '../'
2import locales from './locales'
3
4export let l = (() => {
5 if (__SERVER__) {
6 if (__DEV__ && typeof global.__KOOT_SSR__ === 'object') {
7 if (typeof global.__KOOT_SSR__.locales === 'object')
8 return global.__KOOT_SSR__.locales[localeId]
9 return {}
10 }
11 // console.log({ locales })
12 if (typeof locales === 'object')
13 return locales[localeId]
14 return {}
15 }
16 if (JSON.parse(process.env.KOOT_I18N_TYPE) === 'redux')
17 return locales
18 return false
19})()
20
21/**
22 * 翻译文本
23 * 语言包中源文本中的 ${replaceKey} 表示此处需要替换,replaceKey 就是传入的 obj 中对应的值
24 *
25 * @param {string} key 要翻译的文本 Key
26 * @param {*object} obj 文本内对应的替换内容
27 *
28 * @returns {string} 翻译的文本;如果语言包中没有对应的项,返回 key
29 */
30const translate = (...args) => {
31
32 let key = ''
33 let str
34 let options = {}
35 const keys = []
36
37 if (__SERVER__ && __DEV__) l = locales[global.__KOOT_LOCALEID__]
38
39 args.forEach((value, index) => {
40 if (index == args.length - 1 && typeof value === 'object' && !Array.isArray(value)) {
41 options = value
42 return
43 }
44 if (typeof value === 'string' && value.includes('.')) {
45 value.split('.').forEach(value => keys.push(value))
46 return
47 }
48 keys.push(value)
49 })
50
51 const length = keys.length
52
53 if (typeof keys[0] === 'object') {
54 key = keys[0]
55 for (let i = 1; i < length; i++) {
56 if (typeof key[keys[i]] !== 'undefined')
57 key = key[keys[i]]
58 }
59 if (typeof key === 'object') key = keys[length - 1]
60 } else {
61 for (let i = 0; i < length; i++) {
62 key += (i ? '.' : '') + keys[i]
63 }
64 }
65
66 // if (__CLIENT__) {
67 // // console.log(localeId)
68 // console.log(localeId, keys, length, key, l)
69 // }
70
71 if (typeof l === 'undefined') {
72 str = key
73 } else {
74 str = (l && typeof l[key] !== 'undefined') ? l[key] : undefined
75 }
76 // const localeId = _self.curLocaleId
77
78 if (typeof str === 'undefined') {
79 try {
80 str = eval('l.' + key)
81 } catch (e) { }
82 }
83
84 if (typeof str === 'undefined') str = key
85
86 if (typeof str === 'string')
87 return str.replace(
88 /\$\{([^}]+)\}/g,
89 (match, p) => typeof options[p] === 'undefined' ? p : options[p]
90 )
91 else
92 return str
93}
94export default translate