【问题标题】:Load translations from multiples paths (i18n) in nodejs从节点 js 中的多个路径(i18n)加载翻译
【发布时间】:2020-02-20 15:47:40
【问题描述】:

我使用 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】:
    /**
     * 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,
        },
      });
    

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 2016-03-30
      相关资源
      最近更新 更多