简体   繁体   中英

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:

在此处输入图片说明

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM