从Node.js中的多重路径(i18n)加载翻译

时间:2019-10-24 10:12:12

标签: node.js internationalization i18next

我正在使用i18next处理翻译,并使用i18next-node-fs-backend从文件路径加载翻译。我的i18n.init()函数如下所示:

i18next.use(i18nextBackend)
    .init({
            lng: 'en',
            ns: ['module1, module2],
            backend: {
                loadPath: rootFolder + '/node_modules/{{ns}}/locales/{{lng}}.json',
            }
        }...

我想做的是从该loadPath加载所有翻译,并且还从另一个路径(例如 rootFolder +'/ locales / {{lng}}。json')中的另一个文件加载翻译。 >,就像传递到loadPath参数的路径

loadPath: [rootFolder + '/node_modules/{{ns}}/locales/{{lng}}.json', rootFolder + '/locales/{{lng}}.json']

有可能这样做吗?有什么建议么? 谢谢!!

1 个答案:

答案 0 :(得分:0)

/**
 * Utility function to determine loadpath for a given language and namespace
 * this allows us to separate local files by namespace which makes it easier to
 * find translations and manage them.
 *
 * @param {*} lng the language locale
 * @param {*} namespace the namespace name as specified in the i18n 'ns' config
 */
function loadPath(lng, namespace) {
  // console.log('loadPath', lng, namespace);

  let path = `/locales/common/${lng}/translation.json`;

  /**
   * Add additional case stmts for new locale sub directories.
   * This allows for splitting up translation files into namespaces, namespace can
   * then be attached to a specific component or accessed through notation.
   */
  switch (namespace[0]) {
    case 'common':
      path = `/locales/common/${lng}/translation.json`;
      break;
    case 'container':
      path = `/locales/container/${lng}/translation.json`;
      break;
    default:
      break;
  }
  // console.log('loadPath', path);

  return path;
}

然后在i18n.js配置中

i18n
  .use(Backend) // load translation using xhr -> see /public/locales

  .init({

    // i18next-xhr-backend config for loading files from different locations
    backend: {
      loadPath: loadPath,
    },
  });