Переглянути джерело

feat: enhance language configuration and retrieval

- Add VITE_APP_LANG variable to environment files for language settings
- Update i18n configuration to use environment variable for default language
- Refactor language handling in app store and locales to improve maintainability and support for dynamic language changes
yb 3 тижнів тому
батько
коміт
050cb1146c
6 змінених файлів з 30 додано та 3 видалено
  1. 2 0
      .env
  2. 2 0
      .env.development
  3. 2 0
      .env.production
  4. 10 0
      src/env.d.ts
  5. 10 2
      src/locales/index.ts
  6. 4 1
      src/store/app.ts

+ 2 - 0
.env

@@ -1,5 +1,7 @@
 # 应用标题
 VITE_APP_TITLE=摄像头管理系统
 
+VITE_APP_LANG=zh-cn
+
 # API 基础路径
 VITE_APP_BASE_API=/api

+ 2 - 0
.env.development

@@ -4,5 +4,7 @@ NODE_ENV=development
 # 应用标题
 VITE_APP_TITLE=摄像头管理系统
 
+VITE_APP_LANG=zh-cn
+
 # API 基础路径 (通过 Vite proxy 转发到 https://tg-live-game.pwtk.cc)
 VITE_APP_BASE_API=/api

+ 2 - 0
.env.production

@@ -4,5 +4,7 @@ NODE_ENV=production
 # 应用标题
 VITE_APP_TITLE=摄像头管理系统
 
+VITE_APP_LANG=en
+
 # API 基础路径 (生产环境使用完整 URL,因为 Cloudflare Pages 没有代理)
 VITE_APP_BASE_API=https://tg-live-game.pwtk.cc/api

+ 10 - 0
src/env.d.ts

@@ -1,3 +1,13 @@
 /// <reference types="vite/client" />
 
 declare const __APP_VERSION__: string
+
+interface ImportMetaEnv {
+  readonly VITE_APP_TITLE: string
+  readonly VITE_APP_LANG: string
+  readonly VITE_APP_BASE_API: string
+}
+
+interface ImportMeta {
+  readonly env: ImportMetaEnv
+}

+ 10 - 2
src/locales/index.ts

@@ -11,6 +11,14 @@ const messages = {
   }
 }
 
+// 默认语言从环境变量获取
+const DEFAULT_LANG = import.meta.env.VITE_APP_LANG || 'zh-cn'
+
+// 开发环境下重置语言为环境变量值(方便调试)
+if (import.meta.env.DEV) {
+  localStorage.setItem('language', JSON.stringify(DEFAULT_LANG))
+}
+
 const getCurrentLanguage = () => {
   // 从 localStorage 读取语言设置,与 app store 保持一致
   // useStorage 使用 JSON 序列化,所以需要 parse
@@ -25,7 +33,7 @@ const getCurrentLanguage = () => {
   } catch {
     // ignore parse error
   }
-  return 'zh-cn' // 默认中文
+  return DEFAULT_LANG
 }
 
 const i18n = createI18n({
@@ -33,7 +41,7 @@ const i18n = createI18n({
   globalInjection: true,
   locale: getCurrentLanguage(),
   messages,
-  fallbackLocale: 'zh-cn'
+  fallbackLocale: DEFAULT_LANG
 })
 
 export default i18n

+ 4 - 1
src/store/app.ts

@@ -6,13 +6,16 @@ import zhCn from 'element-plus/es/locale/lang/zh-cn'
 import en from 'element-plus/es/locale/lang/en'
 import i18n from '@/locales'
 
+// 默认语言从环境变量获取
+const DEFAULT_LANG = import.meta.env.VITE_APP_LANG || 'zh-cn'
+
 export const useAppStore = defineStore('app', () => {
   // 侧边栏状态
   const sidebarOpened = ref(true)
   const loading = ref(false)
 
   // 语言和组件尺寸
-  const language = useStorage('language', 'zh-cn')
+  const language = useStorage('language', DEFAULT_LANG)
   const size = ref<'default' | 'small' | 'large'>('default')
 
   /**