首页 > 解决方案 > 在没有覆盖的应用程序之间共享 i18next 实例

问题描述

我目前正在致力于国际化一个使用单水疗(微前端)构建的系统,以及在 Angular 和 React 上编写的应用程序。我开始使用 i18next 并且进展顺利,但是,当我尝试在所有应用程序之间共享 i18next 依赖项时发现了一个问题。

当两个应用程序同时安装在视图上时,最后加载的应用程序会覆盖 i18next 实例,因此永远找不到第一个应用程序的翻译,因为它们没有加载到后者上。

提前致谢!

标签: i18nextmicro-frontendwebpack-externalssingle-spa

解决方案


最好在shell级别使用 shell 命名空间I18next进行初始化,并且每个内部 spa 都会将其命名空间添加到共享实例中。

这样您就不会有重复的实例和代码。

您可以使用 [ i18next.addResourceBundle][1] 来添加与当前内部应用程序相关的翻译资源。


i18next.addResourceBundle('en', 'app1/namespace-1', {
// ----------------------------------^ nested namespace allow you to group namespace by inner apps, and avoid namespace collisions
  key: 'hello from namespace 1'
});

将 i18next 实例作为道具传递给内部应用程序。

// root.application.js

import {i18n} from './i18n';
// ------^ shells i18next configured instance

singleSpa.registerApplication({
  name: 'app1',
  activeWhen,
  app,
  customProps: { i18n, lang: 'en' }
});
// app1.js

export function mount(props) {
  const {i18n, lang} = props;

  i18n.addResourceBundle(lang, 'app1/namespace-1', {
    key: 'hello from namespace 1',
  });
  return reactLifecycles.mount(props);
}

希望这个想法很清楚:] [1]: https://www.i18next.com/how-to/add-or-load-translations#add-after-init


推荐阅读