首页 > 解决方案 > react-i18next - 初始化后如何向 i18n 添加后端?

问题描述

我希望我的 i18n 延迟加载翻译文件,并且从文档中,这样做似乎很简单 - 添加.use(backend)import backend from "i18next-http-backend".

唯一的问题是我在提供的 i18n 实例中已经在我的组织的内部存储库中定义为 UI 库(我必须使用它),它只公开了一种为您初始化 i18n 实例的方法 - 这不会有任何规定.use(backend),现在我被困在如何将其添加到代码中。

这是库代码 -

...

export const getDefaultI18nextInstance = (resources) => {
  i18n
    .use(AlphaLanguageDetector)
    .use(initReactI18next)
    .init({
      fallbackLng: 'en',

      // have a common namespace used around the full app
      ns: [
        'translations',
        'common'
      ],
      nsMode: 'fallback',
      defaultNS: 'translations',

      // debug: (process.env.NODE_ENV && process.env.NODE_ENV === 'production') ? false : true,
      debug: true,

      interpolation: {
        escapeValue: false, // not needed for react!!
      },

      resources: resources || null,

      react: {
        wait: true
      }
    });
    Object.keys(translations).forEach(lang => {
      Object.keys(translations[lang]).forEach(namespace => {
        i18n.addResourceBundle(lang, namespace, translations[lang][namespace], true, true)
      })
    });
  return i18n;
}

export default {
  getDefaultI18nextInstance,
  translations,
  t
};
...

我尝试在我的 index.js 文件中使用类似这样的东西 <I18nextProvider i18n={i18n.getDefaultI18nextInstance().use(backend)}>,但后来我得到了错误

i18next::backendConnector:没有通过 i18next.use 添加后端。不会加载资源。

仅供参考,我的语言环境位于projectRoot/locales/{lang}/translation.json.

标签: reactjsinternationalizationlazy-loadingi18nextreact-i18next

解决方案


您可以使用i18n.cloneInstance(options, callback)并传递您的后端配置 as options,它将合并您的 ui lib 具有的所有选项,并返回一个新的 i18next 实例,该实例将能够获取。

import HttpApi from 'i18next-http-backend';

const original = getDefaultI18nextInstance({});

export const i18n = original
  .cloneInstance({
    backend: {
      loadPath: '/locales/{{lng}}/{{ns}}.json',
    },
  })
  .use(HttpApi);

推荐阅读