index.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { createI18n } from 'vue-i18n'
  2. import EN from './en.json'
  3. import CN from './zh-cn.json'
  4. const messages = {
  5. en: {
  6. ...EN
  7. },
  8. 'zh-cn': {
  9. ...CN
  10. }
  11. }
  12. // 默认语言从环境变量获取
  13. const DEFAULT_LANG = import.meta.env.VITE_APP_LANG || 'zh-cn'
  14. // 开发环境下重置语言为环境变量值(方便调试)
  15. if (import.meta.env.DEV) {
  16. localStorage.setItem('language', JSON.stringify(DEFAULT_LANG))
  17. }
  18. const getCurrentLanguage = () => {
  19. // 从 localStorage 读取语言设置,与 app store 保持一致
  20. // useStorage 使用 JSON 序列化,所以需要 parse
  21. try {
  22. const stored = localStorage.getItem('language')
  23. if (stored) {
  24. const language = JSON.parse(stored)
  25. if (language === 'zh-cn' || language === 'en') {
  26. return language
  27. }
  28. }
  29. } catch {
  30. // ignore parse error
  31. }
  32. return DEFAULT_LANG
  33. }
  34. const i18n = createI18n({
  35. legacy: false,
  36. globalInjection: true,
  37. locale: getCurrentLanguage(),
  38. messages,
  39. fallbackLocale: DEFAULT_LANG
  40. })
  41. export default i18n