我正在使用由 Storybook、React、TypeScript 和 MUI5 构建的设计系统来处理各种应用程序。该设计系统作为一个库捆绑在一起,有自己的一套由 i18next 管理的翻译。在我的主机应用程序中,我也使用相同的技术堆栈和 i18next 进行翻译。
但是,我遇到了一个问题,即导入的设计系统组件中的翻译在主机应用程序中使用时无法正确显示。我只看到翻译键,而不是显示翻译后的文本。主机应用程序中的翻译工作得非常好,甚至手动导入并在主机应用程序中使用的设计系统翻译也能按预期工作。这个问题尤其出现在设计系统中的封装组件上。
为了清晰起见,这是设置的简化版本:
设计系统i18n实例:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import enTranslation from "./locales/en.json";
import deTranslation from "./locales/de.json";
const resources = {
en: {
translation: enTranslation,
},
de: {
translation: deTranslation,
},
};
i18n.use(initReactI18next).init({
resources,
lng: "en",
fallbackLng: "en",
interpolation: {
escapeValue: false,
},
});
export default i18n;
设计系统组件:
import { useTranslation } from "react-i18next";
const DesignSystemComponent = () => {
const { t } = useTranslation();
return( <div>{t('design_system.translation.key')}</div> );
}
主机应用程序 i18n 实例:
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
import en from "./localization/locales/en/en.json";
import de from "./localization/locales/de/de.json";
const detectionOptions = {
order: ["htmlTag"],
};
export type SupportedLanguage = "en" | "de";
const fallbackLng: SupportedLanguage = "en";
i18n
.use(initReactI18next)
.use(LanguageDetector)
.init({
resources: {
en: { translation: en },
de: { translation: de },
},
fallbackLng,
debug: false,
interpolation: {
escapeValue: false,
},
detection: detectionOptions,
});
export default i18n;
主机应用程序组件:
import { useTranslation } from "react-i18next";
import { DesignSystemComponent } from "design-system";
const HostAppComponent = () => {
const { t } = useTranslation();
return(
<>
<div>{t('host_app.translation.key')}</div> // Translation works
<DesignSystemComponent/> // Translation doesn't work
</>
);
}
我已经尝试将设计系统翻译导入到主机应用程序的 i18n 实例中,但没有成功。
如何解决此问题以确保导入的设计系统组件中的翻译在主机应用程序中正确显示?或者,我应该如何在设计系统中实现翻译/本地化,以使其可投入生产并独立于主机系统?