Skip to content

Commit

Permalink
perf: 优化国际化相关处理逻辑,初始化时添加缓存以避免不必要的性能消耗 (#834)
Browse files Browse the repository at this point in the history
Co-authored-by: pengyuhang <[email protected]>
  • Loading branch information
paiz4ever and pengyuhang authored Dec 24, 2023
1 parent 678bd84 commit 792536c
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/plugins/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@ import { storageLocal, isObject } from "@pureadmin/utils";
import enLocale from "element-plus/dist/locale/en.mjs";
import zhLocale from "element-plus/dist/locale/zh-cn.mjs";

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

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

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

Expand All @@ -46,14 +50,25 @@ function getObjectKeys(obj) {
if (obj[k] && isObject(obj[k])) {
stack.push({ obj: obj[k], key: newKey });
} else {
keys.push(newKey);
keys.add(newKey);
}
}
}

return keys;
}

/** 将展开的key缓存 */
const keysCache: Map<string, Set<string>> = new Map();
const flatI18n = (prefix = "zh-CN") => {
let cache = keysCache.get(prefix);
if (!cache) {
cache = getObjectKeys(siphonI18n(prefix));
keysCache.set(prefix, cache);
}
return cache;
};

/**
* 国际化转换工具函数(自动读取根目录locales文件夹下文件进行国际化匹配)
* @param message message
Expand All @@ -73,9 +88,9 @@ export function transformI18n(message: any = "") {

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

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

1 comment on commit 792536c

@jack20211101
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Please sign in to comment.