【问题标题】:Create React App - loading i18n translations from relative path创建 React 应用程序 - 从相对路径加载 i18n 翻译
【发布时间】:2020-10-18 00:04:05
【问题描述】:

我的 React 应用程序通过在 package.json 中设置 homepage 变量从相对路径加载。然而 i18next-http-backend 仍然尝试从 http://localhost:3000/locales/en/translation.json 而不是 http://localhost:3000/myapp/locales/en/translation.json 加载翻译。我什至尝试设置 loadPath 选项(虽然不确定语法),但这不起作用。请看下面:

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,
    loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json`,

    interpolation: {
      escapeValue: false // not needed for react as it escapes by default
    }
  })

我怎样才能做到这一点?

【问题讨论】:

  • 你的 locales 文件夹在 public 文件夹下吗?
  • 是的。翻译文件位于:/public/locales/en/translation.json
  • loadPath 应该在后端对象下。我的意思是你必须在你的初始化中有这样的东西 {debug: true, backend: {loadPath: ""}}

标签: create-react-app react-i18next i18next-http-backend


【解决方案1】:

loadPath 需要设置为Backend 初始化的一部分,因此您需要执行以下操作...

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,
    backend: {
        loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json`,
    }
    interpolation: {
      escapeValue: false // not needed for react as it escapes by default
    }
  })

【讨论】:

  • 你让我很开心 :-)
猜你喜欢
  • 2020-02-20
  • 2020-10-31
  • 2019-10-04
  • 2017-10-09
  • 2021-09-30
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 2018-11-25
相关资源
最近更新 更多