main.tsx 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import React from 'react';
  2. import dayjs from 'dayjs';
  3. import utc from 'dayjs/plugin/utc';
  4. import ReactDOM from 'react-dom/client';
  5. import { I18nextProvider } from 'react-i18next';
  6. import './i18n';
  7. import './styles/antd.scss';
  8. import './styles/global.scss';
  9. import './styles/tailwind.css';
  10. import App from './App';
  11. import i18n from './i18n';
  12. // 配置 dayjs
  13. dayjs.extend(utc);
  14. // 更新 URL 中的语言参数
  15. const updateUrlLang = (language: string) => {
  16. const url = new URL(window.location.href);
  17. const hash = url.hash;
  18. // 移除 URL 中的 lang 参数
  19. url.searchParams.delete('lang');
  20. if (hash) {
  21. // Hash 路由模式
  22. const [path, search] = hash.split('?');
  23. const params = new URLSearchParams(search || '');
  24. params.set('lang', language);
  25. url.hash = `${path}?${params.toString()}`;
  26. } else {
  27. // 普通路由模式
  28. url.searchParams.set('lang', language);
  29. }
  30. window.history.replaceState({}, '', url.toString());
  31. };
  32. // 设置文档方向
  33. const setDocumentDirection = (language: string) => {
  34. const direction = i18n.t('DIR') === 'rtl' ? 'rtl' : 'ltr';
  35. document.documentElement.dir = direction;
  36. document.documentElement.lang = language;
  37. // 更新 URL 中的语言参数
  38. updateUrlLang(language);
  39. };
  40. // 监听语言变化
  41. i18n.on('languageChanged', setDocumentDirection);
  42. // 初始化时只设置文档方向,不更新 URL
  43. const initDocumentDirection = (language: string) => {
  44. const direction = i18n.t('DIR') === 'rtl' ? 'rtl' : 'ltr';
  45. document.documentElement.dir = direction;
  46. document.documentElement.lang = language;
  47. };
  48. // 初始化时设置方向
  49. initDocumentDirection(i18n.language);
  50. ReactDOM.createRoot(document.getElementById('root')!).render(
  51. <React.StrictMode>
  52. <I18nextProvider i18n={i18n}>
  53. <App />
  54. </I18nextProvider>
  55. </React.StrictMode>
  56. );