1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | function generateI18nData(sourceData) {
|
23 | const locales = {};
|
24 |
|
25 | Object.keys(sourceData).forEach((key) => {
|
26 | locales[key] = parseI18NString(sourceData[key]);
|
27 | });
|
28 |
|
29 | return mergeI18N(locales);
|
30 | }
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 |
|
45 |
|
46 | function parseI18NString(i18nStr) {
|
47 |
|
48 | const flagReg = /(.*)(\[([a-z]+-[A-Z]+)\])(.*)/;
|
49 | const cnReg = /[\u4e00-\u9fa5]+/g;
|
50 | const local = {};
|
51 |
|
52 | parseString(i18nStr);
|
53 |
|
54 | return local;
|
55 |
|
56 |
|
57 | function parseString(str = '') {
|
58 | const match = flagReg.exec(str);
|
59 |
|
60 | if (!match) {
|
61 | if (cnReg.test(str)) {
|
62 | local['zh-CN'] = str.trim();
|
63 | } else {
|
64 | local['en-US'] = str.trim();
|
65 | }
|
66 | return;
|
67 | }
|
68 |
|
69 | const [, $1, , $3, $4] = match;
|
70 | local[$3] = $4.trim();
|
71 |
|
72 | if ($1) {
|
73 | parseString($1);
|
74 | }
|
75 | }
|
76 | }
|
77 |
|
78 |
|
79 |
|
80 |
|
81 |
|
82 |
|
83 |
|
84 | function mergeI18N(sourceData) {
|
85 | const locales = {
|
86 | 'zh-CN': {},
|
87 | 'en-US': {},
|
88 | };
|
89 |
|
90 | Object.keys(sourceData).forEach((key) => {
|
91 | const i18nObj = sourceData[key];
|
92 | Object.keys(i18nObj).forEach((lang) => {
|
93 | if (locales[lang]) {
|
94 | locales[lang][key] = i18nObj[lang];
|
95 | } else {
|
96 | locales[lang] = {
|
97 | [key]: i18nObj[lang],
|
98 | };
|
99 | }
|
100 | });
|
101 | });
|
102 |
|
103 | return locales;
|
104 | }
|
105 |
|
106 | module.exports = generateI18nData;
|