Sharing i18next instance between applications without override

2.6k Views Asked by At

I'm currently working on internationalizing a system built with single-spa (microfrontends) with applications written on Angular and React. I started using i18next and it's going pretty well, however, I've found a problem when trying to share the i18next dependency between all the applications.

When two applications are mounted simultaneously on the view the one who loads last overrides the i18next instance and thus the translations for the first one are never found as they were not loaded on the latter.

Thanks in advance!

1

There are 1 best solutions below

6
On BEST ANSWER

It is better that I18next will be initialized at the shell level with the shell namespaces, and each internal spa will add its namespaces to the shared instance.

This way you won't have duplication of instance & code.

You can use [i18next.addResourceBundle][1] in order to add translation resources that are related to the current inner app.


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'
});

Pass the i18next instance as props to the inner app.

// 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);
}

Hope that the idea is clear :] [1]: https://www.i18next.com/how-to/add-or-load-translations#add-after-init