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

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

我用 create-react-app

创建了一个 React 应用程序

我想实现翻译,我发现了 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 文件夹中。

希望对您有所帮助!

以防万一有人像我一样需要这个:

如果您碰巧像这样更改了 package.json 文件中的主页路径:

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

你还需要像这样将这部分添加到 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;