@@ -8,16 +8,20 @@ import { storageLocal, isObject } from "@pureadmin/utils";
8
8
import enLocale from "element-plus/dist/locale/en.mjs" ;
9
9
import zhLocale from "element-plus/dist/locale/zh-cn.mjs" ;
10
10
11
- function siphonI18n ( prefix = "zh-CN" ) {
12
- return Object . fromEntries (
11
+ const siphonI18n = ( function ( ) {
12
+ // 仅初始化一次国际化配置
13
+ let cache = Object . fromEntries (
13
14
Object . entries (
14
15
import . meta. glob ( "../../locales/*.y(a)?ml" , { eager : true } )
15
16
) . map ( ( [ key , value ] : any ) => {
16
17
const matched = key . match ( / ( [ A - Z a - z 0 - 9 - _ ] + ) \. / i) [ 1 ] ;
17
18
return [ matched , value . default ] ;
18
19
} )
19
- ) [ prefix ] ;
20
- }
20
+ ) ;
21
+ return ( prefix = "zh-CN" ) => {
22
+ return cache [ prefix ] ;
23
+ } ;
24
+ } ) ( ) ;
21
25
22
26
export const localesConfigs = {
23
27
zh : {
@@ -33,7 +37,7 @@ export const localesConfigs = {
33
37
/** 获取对象中所有嵌套对象的key键,并将它们用点号分割组成字符串 */
34
38
function getObjectKeys ( obj ) {
35
39
const stack = [ ] ;
36
- const keys = [ ] ;
40
+ const keys : Set < string > = new Set ( ) ;
37
41
38
42
stack . push ( { obj, key : "" } ) ;
39
43
@@ -46,14 +50,25 @@ function getObjectKeys(obj) {
46
50
if ( obj [ k ] && isObject ( obj [ k ] ) ) {
47
51
stack . push ( { obj : obj [ k ] , key : newKey } ) ;
48
52
} else {
49
- keys . push ( newKey ) ;
53
+ keys . add ( newKey ) ;
50
54
}
51
55
}
52
56
}
53
57
54
58
return keys ;
55
59
}
56
60
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
+
57
72
/**
58
73
* 国际化转换工具函数(自动读取根目录locales文件夹下文件进行国际化匹配)
59
74
* @param message message
@@ -73,9 +88,9 @@ export function transformI18n(message: any = "") {
73
88
74
89
const key = message . match ( / ( \S * ) \. / ) ?. input ;
75
90
76
- if ( key && getObjectKeys ( siphonI18n ( "zh-CN" ) ) . find ( item => item === key ) ) {
91
+ if ( key && flatI18n ( "zh-CN" ) . has ( key ) ) {
77
92
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 ) ) {
79
94
// 兼容非嵌套形式的国际化写法
80
95
return i18n . global . t . call ( i18n . global . locale , message ) ;
81
96
} else {
0 commit comments