我在决定如何处理我的语言应用程序时遇到了一些麻烦。正如您在下面看到的,我使用“window.localStorage.setItem(LOCAL_STORAGE_KEY, locale);” 获取浏览器的语言环境。我有两种语言es和en。但是,当某人使用另一种不是 es 或 en 的语言时,例如当它检测到具有语言环境继承的语言时,例如:“es-ES”
(在此处传递:(/imports/cuadds/both/locales/${locale}/messages
))我收到以下错误:
Error: Cannot find module '/imports/cuadds/both/locales/es-ES/messages'
当找不到语言时,如何创建使语言环境默认为 en 或 es 的函数?
import { i18n } from "@lingui/core";
import { detect, fromStorage, fromNavigator } from "@lingui/detect-locale";
import { en, es } from "make-plural/plurals";
let isActivated;
const startupI18n = () => {
if (isActivated) return;
isActivated = true;
i18n.loadLocaleData({
en: { plurals: en },
es: { plurals: es },
});
dynamicActivate(getLocale());
};
export default startupI18n;
const LOCAL_STORAGE_KEY = "lang";
// defines where the locale falls back to (passed to dynamicActivate)
const DEFAULT_LOCALE = "es";
/**
* Load messages for requested locale and activate it.
*/
export async function dynamicActivate(locale) {
try {
const module = await import(`/imports/cuadds/both/locales/${locale}/messages`);
i18n.load(locale, module.messages);
i18n.activate(locale);
// saves the language to the localStorage
window.localStorage.setItem(LOCAL_STORAGE_KEY, locale);
} catch (error) {
console.log(error);
}
};
function getLocale() {
const detectedLocale = detect(
fromStorage("LOCAL_STORAGE_KEY"),
fromNavigator(),
DEFAULT_LOCALE,
);
return detectedLocale;
}