* 加载单个模块
(locale: string, moduleName: string)
| 79 | * 加载单个模块 |
| 80 | */ |
| 81 | async loadModule(locale: string, moduleName: string): Promise<any> { |
| 82 | const cacheKey = `${locale}:${moduleName}`; |
| 83 | |
| 84 | // 检查缓存 |
| 85 | if (this.cache.has(cacheKey)) { |
| 86 | return this.cache.get(cacheKey); |
| 87 | } |
| 88 | |
| 89 | const moduleInfo = this.moduleRegistry.get(moduleName); |
| 90 | if (!moduleInfo) { |
| 91 | console.warn(`模块 ${moduleName} 未注册`); |
| 92 | return {}; |
| 93 | } |
| 94 | |
| 95 | try { |
| 96 | // 使用动态import加载JSON文件,兼容构建和开发环境 |
| 97 | const modulePath = `../locales/${locale}/${moduleInfo.path}`; |
| 98 | const module = await import(/* @vite-ignore */ modulePath); |
| 99 | const data = module.default || module; |
| 100 | |
| 101 | // 缓存结果 |
| 102 | this.cache.set(cacheKey, data); |
| 103 | |
| 104 | // 更新模块信息 |
| 105 | moduleInfo.loaded = true; |
| 106 | moduleInfo.data = data; |
| 107 | |
| 108 | return data; |
| 109 | } catch (error) { |
| 110 | console.error(`加载模块 ${moduleName} 失败:`, error); |
| 111 | |
| 112 | // 回退方案:尝试使用fetch(开发环境) |
| 113 | try { |
| 114 | const modulePath = `/src/i18n/locales/${locale}/${moduleInfo.path}`; |
| 115 | const response = await fetch(modulePath); |
| 116 | |
| 117 | if (!response.ok) { |
| 118 | throw new Error(`HTTP ${response.status}: ${response.statusText}`); |
| 119 | } |
| 120 | |
| 121 | const data = await response.json(); |
| 122 | |
| 123 | // 缓存结果 |
| 124 | this.cache.set(cacheKey, data); |
| 125 | |
| 126 | // 更新模块信息 |
| 127 | moduleInfo.loaded = true; |
| 128 | moduleInfo.data = data; |
| 129 | |
| 130 | return data; |
| 131 | } catch (fetchError) { |
| 132 | console.error(`回退fetch加载也失败:`, fetchError); |
| 133 | return {}; |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | /** |
no test coverage detected