feat: use resourcesToBackend to load i18n files (#2755)

This commit is contained in:
DacongDA 2024-02-28 01:43:55 +08:00 committed by GitHub
parent 6c76913f71
commit 78af5daec3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -13,57 +13,34 @@
// limitations under the License.
import i18n from "i18next";
import en from "./locales/en/data.json";
import zh from "./locales/zh/data.json";
import es from "./locales/es/data.json";
import fr from "./locales/fr/data.json";
import de from "./locales/de/data.json";
import id from "./locales/id/data.json";
import ja from "./locales/ja/data.json";
import ko from "./locales/ko/data.json";
import ru from "./locales/ru/data.json";
import vi from "./locales/vi/data.json";
import pt from "./locales/pt/data.json";
import it from "./locales/it/data.json";
import ms from "./locales/ms/data.json";
import tr from "./locales/tr/data.json";
import ar from "./locales/ar/data.json";
import he from "./locales/he/data.json";
import nl from "./locales/nl/data.json";
import pl from "./locales/pl/data.json";
import fi from "./locales/fi/data.json";
import sv from "./locales/sv/data.json";
import uk from "./locales/uk/data.json";
import kk from "./locales/kk/data.json";
import fa from "./locales/fa/data.json";
import * as Conf from "./Conf";
import {initReactI18next} from "react-i18next";
import en from "./locales/en/data.json";
const resources = {
en: en,
zh: zh,
es: es,
fr: fr,
de: de,
id: id,
ja: ja,
ko: ko,
ru: ru,
vi: vi,
pt: pt,
it: it,
ms: ms,
tr: tr,
ar: ar,
he: he,
nl: nl,
pl: pl,
fi: fi,
sv: sv,
uk: uk,
kk: kk,
fa: fa,
};
const resourcesToBackend = (res) => ({
type: "backend",
init(services, backendOptions, i18nextOptions) {/* use services and options */},
read(language, namespace, callback) {
if (typeof res === "function") {
if (res.length < 3) {
try {
const r = res(language, namespace);
if (r && typeof r.then === "function") {
r.then((data) => callback(null, (data && data.default) || data)).catch(callback);
} else {
callback(null, r);
}
} catch (err) {
callback(err);
}
return;
}
res(language, namespace, callback);
return;
}
callback(null, res && res[language] && res[language][namespace]);
},
});
function initLanguage() {
let language = localStorage.getItem("language");
@ -157,10 +134,16 @@ function initLanguage() {
return language;
}
i18n.use(initReactI18next).init({
i18n.use(resourcesToBackend(async(language, namespace) => {
const res = await import(`./locales/${language}/data.json`);
return res.default[namespace];
}
))
.use(initReactI18next)
.init({
lng: initLanguage(),
resources: resources,
ns: Object.keys(en),
fallbackLng: "en",
keySeparator: false,
@ -169,6 +152,5 @@ i18n.use(initReactI18next).init({
},
// debug: true,
saveMissing: true,
});
});
export default i18n;