Skip to content

Commit

Permalink
i18n: aync load lang file
Browse files Browse the repository at this point in the history
  • Loading branch information
cnwhy committed Jun 14, 2024
1 parent d9692b3 commit c47e44a
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 11 deletions.
9 changes: 9 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"events": "^3.3.0",
"i18next": "^23.11.5",
"i18next-browser-languagedetector": "^8.0.0",
"i18next-resources-to-backend": "^1.2.1",
"idb": "^7.1.1",
"idb-open-plus": "^1.0.0",
"jsonc-parser": "^3.2.0",
Expand Down
12 changes: 10 additions & 2 deletions src/components/Language.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import { Button, ButtonProps } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";

export const LanguageButton = (props: ButtonProps) => {
const { i18n } = useTranslation();
const [isLoading, setLoading] = useState(false);
(window as any).i18n = i18n;
return (
<Button
loading={isLoading}
shape="circle"
{...props}
onClick={() => {
i18n.changeLanguage(i18n.resolvedLanguage === "en" ? "zh" : "en");
setLoading(true);
i18n
.changeLanguage(i18n.resolvedLanguage === "en" ? "zh-cn" : "en")
// .then(()=>console.log('changeLanguage ok'), (err) => console.error(err))
.finally(() => setLoading(false));
}}
>
{i18n.resolvedLanguage === "en" ? "中" : "En"}
{isLoading ? "" : i18n.resolvedLanguage === "en" ? "中" : "En"}
</Button>
);
};
16 changes: 7 additions & 9 deletions src/uitls/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,28 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import resourcesToBackend from "i18next-resources-to-backend";
import { isValidElement } from "react";
import en from '../i18n/en.json';
import zh from '../i18n/zh.json';
// const en = await import("../i18n/en.json");
// const zh = await import("../i18n/zh.json");

const fallbackLng = "en";
i18n
// 检测用户当前使用的语言
// 文档: https://github.com/i18next/i18next-browser-languageDetector
.use(LanguageDetector)
// 注入 react-i18next 实例
.use(initReactI18next)
// 动态加载语言包
.use(
resourcesToBackend((language:string, namespace:string) => import(`../i18n/${language}.json`))
)
// 初始化 i18next
// 配置参数的文档: https://www.i18next.com/overview/configuration-options
.init({
debug: true,
debug: import.meta.env.DEV,
fallbackLng: fallbackLng,
interpolation: {
escapeValue: false,
},
resources: {
en: { translation: en },
zh: { translation: zh },
},
});

export function getLabel(label: string | { [key: string]: string }) {
Expand Down

0 comments on commit c47e44a

Please sign in to comment.