所有页面-创建中英双语对照-优化翻译文档结构

This commit is contained in:
2026-03-17 11:42:16 +08:00
parent 4a7397ce04
commit c790f74905
110 changed files with 1729 additions and 421 deletions

View File

@@ -0,0 +1,84 @@
/**
* 按路由加载页面级翻译到 page 命名空间
* 路由 /dice/lottery_pool_config/index -> 加载 langs/{locale}/dice/lottery_pool_config.json
*/
import i18n from '@/locales'
import { LanguageEnum } from '@/enums/appEnum'
/** 路由 path 到 locale 文件路径的映射(无前导斜杠、无 /index */
export function getPageLocalePath(routePath: string): string | null {
if (!routePath || routePath === '/') return null
const normalized = routePath.replace(/\?.*$/, '').replace(/#.*$/, '').replace(/\/$/, '')
const withoutIndex = normalized.replace(/\/index$/i, '') || '/'
const path = withoutIndex.replace(/^\//, '') || ''
if (!path) return null
return path
}
type PageLocaleModule = { default: Record<string, unknown> }
const enModules = import.meta.glob<PageLocaleModule>('./langs/en/**/*.json')
const zhModules = import.meta.glob<PageLocaleModule>('./langs/zh/**/*.json')
function getModuleKey(locale: string, path: string): string {
return `./langs/${locale}/${path}.json`
}
let lastLoadedPath: string | null = null
let lastLoadedLocale: string | null = null
/**
* 加载并合并页面翻译到 i18n 的 page 命名空间
*/
export async function loadPageLocale(routePath: string): Promise<void> {
const path = getPageLocalePath(routePath)
if (!path) {
clearPageLocale()
return
}
const locale = i18n.global.locale.value
const key = getModuleKey(locale, path)
const modules = locale === LanguageEnum.EN ? enModules : zhModules
const loader = modules[key]
if (!loader) {
clearPageLocale()
return
}
if (lastLoadedPath === path && lastLoadedLocale === locale) {
return
}
try {
const mod = await loader()
const message = mod?.default
if (message && typeof message === 'object') {
i18n.global.mergeLocaleMessage(locale, { page: message })
lastLoadedPath = path
lastLoadedLocale = locale
}
} catch {
clearPageLocale()
}
}
/**
* 清除 page 命名空间(进入无页面翻译的路由时调用)
*/
export function clearPageLocale(): void {
const locale = i18n.global.locale.value
const messages = i18n.global.getLocaleMessage(locale) as Record<string, unknown>
if (messages && 'page' in messages) {
const next = { ...messages }
delete next.page
i18n.global.setLocaleMessage(locale, next)
}
lastLoadedPath = null
lastLoadedLocale = null
}
/**
* 语言切换时清空缓存,下次进入页面会重新加载
*/
export function invalidatePageLocaleCache(): void {
lastLoadedPath = null
lastLoadedLocale = null
}