首页 > 解决方案 > 无法在 i18next 中使用来自 S3 buck 的 JSON

问题描述

这就是我的i18n文件的样子 -

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import HttpApi from 'i18next-http-backend';

i18n
  .use(HttpApi)
  .use(initReactI18next)
  .init({
    // resources: resourcesObj,
    initImmediate: false,
    backend: {
      loadPath: 'https://bucketlink.amazonaws.com/locales/{{lng}}/{{ns}}.json',
      crossDomain: true,
      allowMultiLoading: true,
    },
    lng: "en",
    fallbackLng: "en",
    debug: false,
    ns: ["translations"],
    defaultNS: "translations",
    keySeparator: false,
    interpolation: {
      escapeValue: true
    }
  });

export default i18n;

当我更改语言时,我看到我的网络选项卡显示 JSON 正确来自 S3。但是,在我的所有屏幕中都显示了键而不是值。有人可以告诉我为什么我的翻译值没有显示。

注意——如果我使用资源并将我的 json 对象放入其中,它会按预期工作。

标签: reactjsi18nextreact-intlreact-i18next

解决方案


从您发布的演示中,问题是您的 json 文件(存储在 s3 中的文件)的格式不正确。

您需要按 lang & 命名空间(translations在您的情况下)拆分 json 文件,并且 json 文件必须仅包含与lang&相关的键namespace

例如,您的文件夹应如下所示:

└── locales
    ├── en
    │   └── translations.json
    └── he
        └── translations.json

每个translation.json文件应包含:

{ 
  "Overview": "Overview",
  "TaskList": "Task List"
}

PS,你的翻译文件可以是一个嵌套对象,那么你需要用一个dot notation(类似的东西a.b.c)指定键


推荐阅读