react-i18next不会在使用create-react-app创建的React应用程序中加载json转换文件 [英] react-i18next not loading json translation files in React app created with create-react-app

查看:364
本文介绍了react-i18next不会在使用create-react-app创建的React应用程序中加载json转换文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 create-react-app

我想实施翻译,并且发现了 react-i18next

安装必需的软件包后,我已经设置了我的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;

我收到此错误:i18next::backendConnector: loading namespace translation for language en failed failed parsing locales/en/translation.json to json

发生这种情况是因为webpack找不到json文件,而是返回了index.html文件内容:

解决方案

我不确定您将语言环境文件放在何处,但是我看到两个问题:

  1. 您已指定一个相对URL,因此您加载/kiosk/parents/locales而不是/locales.您需要在加载路径的开头添加一个斜杠.

  2. 要让Create React App提供静态文件,您需要将其放入public文件夹.这在其用户指南中有更详细的描述.因此,请确保locales在项目根目录的public文件夹中.

希望这会有所帮助!

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!

这篇关于react-i18next不会在使用create-react-app创建的React应用程序中加载json转换文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆