You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.0 KiB

5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
5 months ago
  1. import { changeLanguage } from '@/store/system.ts'
  2. import i18n, { InitOptions, t } from 'i18next'
  3. import LanguageDetector from 'i18next-browser-languagedetector'
  4. import { initReactI18next, useTranslation, } from 'react-i18next'
  5. import { zh, en } from './locales'
  6. import { ProColumns } from '@ant-design/pro-components'
  7. const detectionOptions = {
  8. // 探测器的选项
  9. order: [ 'querystring', 'cookie', 'localStorage', 'navigator', 'htmlTag' ],
  10. lookupQuerystring: 'lng',
  11. lookupCookie: 'i18next',
  12. lookupLocalStorage: 'i18nextLng',
  13. caches: [ 'localStorage', 'cookie' ],
  14. excludeCacheFor: [ 'cimode' ], // 语言探测模式中排除缓存的语言
  15. }
  16. export const initI18n = (options?: InitOptions) => {
  17. i18n.on('initialized', () => {
  18. const currentLanguage = i18n.language
  19. changeLanguage(currentLanguage)
  20. })
  21. return i18n
  22. .use(initReactI18next)
  23. .use(LanguageDetector)
  24. .init({
  25. resources: {
  26. en: {
  27. translation: en.default,
  28. },
  29. zh: {
  30. translation: zh.default,
  31. },
  32. },
  33. fallbackLng: 'zh',
  34. debug: false,
  35. detection: detectionOptions,
  36. interpolation: {
  37. escapeValue: false,
  38. },
  39. ...options,
  40. })
  41. }
  42. export function getI18nTitle(key: string, defTitle: string): string;
  43. export function getI18nTitle(key: string, column: ProColumns): string;
  44. export function getI18nTitle(key: string, option: any): string {
  45. if (option.dataIndex) {
  46. let k = `${key}.columns.${option.dataIndex}`
  47. if (option.i18n) {
  48. k = option.i18n
  49. }
  50. //如果没有key也没有option.i18n, 说明没有i18n前缀, 直接返回
  51. if (!option.i18n && !key) {
  52. return option.title || option.label
  53. }
  54. return t(k, (option.title || option.label) as string)
  55. }
  56. if (!key) {
  57. return option as unknown as string
  58. }
  59. return t(`${key}`, option as unknown as string)
  60. }
  61. export {
  62. useTranslation, t
  63. }
  64. export default i18n