Gerardo Quiros
Gerardo Quiros

Reputation: 53

Load translations from multiples paths (i18n) in nodejs

I'm using i18next to handle translations, with i18next-node-fs-backend, to load translations from a filepath. My i18n.init() function looks like this:

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

What i want to do is load all translations from that loadPath AND also load the translations from another file, located in another path, like rootFolder + '/locales/{{lng}}.json', like passing to path to loadPath parameter

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

Is it possible to do that? Any suggestions? Thanks.!

Upvotes: 2

Views: 3318

Answers (1)

olaf
olaf

Reputation: 31

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

then in i18n.js configuration

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

  .init({

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

Upvotes: 0

Related Questions