Skip to content

Commit 792536c

Browse files
paiz4everpengyuhang
andauthored
perf: 优化国际化相关处理逻辑,初始化时添加缓存以避免不必要的性能消耗 (#834)
Co-authored-by: pengyuhang <[email protected]>
1 parent 678bd84 commit 792536c

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

src/plugins/i18n.ts

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,20 @@ import { storageLocal, isObject } from "@pureadmin/utils";
88
import enLocale from "element-plus/dist/locale/en.mjs";
99
import zhLocale from "element-plus/dist/locale/zh-cn.mjs";
1010

11-
function siphonI18n(prefix = "zh-CN") {
12-
return Object.fromEntries(
11+
const siphonI18n = (function () {
12+
// 仅初始化一次国际化配置
13+
let cache = Object.fromEntries(
1314
Object.entries(
1415
import.meta.glob("../../locales/*.y(a)?ml", { eager: true })
1516
).map(([key, value]: any) => {
1617
const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1];
1718
return [matched, value.default];
1819
})
19-
)[prefix];
20-
}
20+
);
21+
return (prefix = "zh-CN") => {
22+
return cache[prefix];
23+
};
24+
})();
2125

2226
export const localesConfigs = {
2327
zh: {
@@ -33,7 +37,7 @@ export const localesConfigs = {
3337
/** 获取对象中所有嵌套对象的key键,并将它们用点号分割组成字符串 */
3438
function getObjectKeys(obj) {
3539
const stack = [];
36-
const keys = [];
40+
const keys: Set<string> = new Set();
3741

3842
stack.push({ obj, key: "" });
3943

@@ -46,14 +50,25 @@ function getObjectKeys(obj) {
4650
if (obj[k] && isObject(obj[k])) {
4751
stack.push({ obj: obj[k], key: newKey });
4852
} else {
49-
keys.push(newKey);
53+
keys.add(newKey);
5054
}
5155
}
5256
}
5357

5458
return keys;
5559
}
5660

61+
/** 将展开的key缓存 */
62+
const keysCache: Map<string, Set<string>> = new Map();
63+
const flatI18n = (prefix = "zh-CN") => {
64+
let cache = keysCache.get(prefix);
65+
if (!cache) {
66+
cache = getObjectKeys(siphonI18n(prefix));
67+
keysCache.set(prefix, cache);
68+
}
69+
return cache;
70+
};
71+
5772
/**
5873
* 国际化转换工具函数(自动读取根目录locales文件夹下文件进行国际化匹配)
5974
* @param message message
@@ -73,9 +88,9 @@ export function transformI18n(message: any = "") {
7388

7489
const key = message.match(/(\S*)\./)?.input;
7590

76-
if (key && getObjectKeys(siphonI18n("zh-CN")).find(item => item === key)) {
91+
if (key && flatI18n("zh-CN").has(key)) {
7792
return i18n.global.t.call(i18n.global.locale, message);
78-
} else if (!key && Object.keys(siphonI18n("zh-CN")).includes(message)) {
93+
} else if (!key && Object.hasOwn(siphonI18n("zh-CN"), message)) {
7994
// 兼容非嵌套形式的国际化写法
8095
return i18n.global.t.call(i18n.global.locale, message);
8196
} else {

0 commit comments

Comments
 (0)