Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-i18next not loading json translation files in React app created with create-react-app

I've created a React application with create-react-app

I want to implement translations and I've discovered react-i18next

After installing required packages I've setup my i18n.js config file:

import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import XHR from 'i18next-xhr-backend';

i18n
    .use(XHR)
    .use(LanguageDetector)
    .init({
      debug: true,
      lng: 'en',
      nsSeparator: false,
      keySeparator: false,
      fallbackLng: false,
      backend: {
        loadPath: 'locales/{{lng}}/{{ns}}.json'
      }
    });


export default i18n;

I'm getting this error: i18next::backendConnector: loading namespace translation for language en failed failed parsing locales/en/translation.json to json

It happens because webpack doesn't find the json file and is returning the index.html file contents instead:

enter image description here

like image 403
Cristian Rojas Avatar asked May 10 '17 16:05

Cristian Rojas


2 Answers

I'm not sure where you put the locale files, but I see two issues:

  1. You have specified a relative URL so you load /kiosk/parents/locales rather than /locales. You need to add a slash at the beginning of the load path.

  2. For Create React App to serve static files, you need to put them into the public folder. This is described in its User Guide in more detail. So make sure locales is inside the public folder in the project root.

Hope this helps!

like image 104
Dan Abramov Avatar answered Oct 27 '22 12:10

Dan Abramov


Just in case anyone needs this like I did:

If you happen to have changed your homepage path in your package.json file like so:

...
    "homepage": "/tom/",
...

you also need to add this part to i18n like so:

i18n
    .use(XHR)
    .use(LanguageDetector)
    .init({
      debug: true,
      lng: 'en',
      nsSeparator: false,
      keySeparator: false,
      fallbackLng: false,
      backend: {
        loadPath: '/tom/locales/{{lng}}/{{ns}}.json'
      }
    });


export default i18n;
like image 37
theRealEmu Avatar answered Oct 27 '22 14:10

theRealEmu