从nodejs中的多重路径(i18n)加载转换

问题描述 投票:0回答:1

我正在使用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']

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

node.js internationalization i18next
1个回答
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,
    },
  });
© www.soinside.com 2019 - 2024. All rights reserved.