简体   繁体   English

react-i18next 未在使用 create-react-app 创建的 React 应用程序中加载 json 翻译文件

[英]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我用create-react-app创建了一个 React 应用程序

I want to implement translations and I've discovered react-i18next我想实现翻译,我发现了react-i18next

After installing required packages I've setup my i18n.js config file:安装所需的软件包后,我已经设置了 i18n.js 配置文件:

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我收到此错误: 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:发生这种情况是因为 webpack 没有找到 json 文件,而是返回 index.html 文件内容:

在此处输入图片说明

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 .您已指定一个相对 URL,因此您加载/kiosk/parents/locales而不是/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.对于 Create React App 来提供静态文件,您需要将它们放入public文件夹。 This is described in its User Guide in more detail.这在其用户指南中有更详细的描述。 So make sure locales is inside the public folder in the project root.因此,请确保locales位于项目根目录的public文件夹内。

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:如果您碰巧在 package.json 文件中更改了主页路径,如下所示:

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

you also need to add this part to i18n like so:您还需要将此部分添加到 i18n,如下所示:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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