Can I put the locales folder containing JSON files for each language in a custom directory outside public folder while using react-i18next? How to configure the same?

I am also using lazy loading and caching.

Things work when the locales folder is inside public folder like this: enter image description here

But does not work as soon as I move it outside public folder like this: enter image description here

No luck after changing loadPath also.

My i18n.js looks like this:

`

import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import ChainedBackend from "i18next-chained-backend";
import HttpBackend from "i18next-http-backend";
import LocalStorageBackend from "i18next-localstorage-backend";

i18n
  .use(initReactI18next)
  .use(ChainedBackend)
  .init({
    lng: 'hi_IN',
    

    interpolation: {
      escapeValue: false,
    },
    react: {
      useSuspense: true,
    },
    saveMissing: true,
    backend: {
        backends: [
          LocalStorageBackend,
          HttpBackend
        ],
        backendOptions: [{
          expirationTime: 7 * 24 * 60 * 60 * 1000
        }, {
          loadPath: '../src/locales/{{lng}}/{{ns}}.json',
        }]
      }
  });

  export default i18n;

`

Thank you.

I tried changing loadPath and addPath, I searched through StackOverflow and Google. Went through the docs, but no luck.

1

There are 1 best solutions below

0
On

yes you can, in order to load from 'src/locales' , you need to import the folder and set as a resources into the i18n init config as shown below:

import resources from './locales';

your i18n file in src folder as:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import resources from './locales';

// NOTE: no i18next-http-backend is used because for a library it does not work to load locales from public folder
i18n
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    resources,  // <------------- HERE IS THE CHANGE
    // Allows "en-US" and "en-UK" to be implicitly supported when "en" is supported
    nonExplicitSupportedLngs: true,
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    react: {
      useSuspense: true,
    },
    debug: process.env.NODE_ENV === 'development',
  });

export default i18n;