创建 React App - 从相对路径加载 i18n 翻译

Nar*_*esh 2 create-react-app react-i18next i18next-http-backend

我的 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
    }
  })
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

小智 8

需要将其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
    }
  })
Run Code Online (Sandbox Code Playgroud)