react-i18next仅在构建中给出了missingKey错误

时间:2020-07-22 15:35:23

标签: reactjs i18next react-i18next

enter image description here

下面是我的index.jsi18next.js(i18n的配置)

index.js

import React, { Suspense } from 'react'
import i18n from './i18next'
import './i18next'
import ReactDOM from 'react-dom'
import App from './App'
import * as serviceWorker from './serviceWorker'
import Loading from './components/Styled/Loading/Loading'

i18n.init().then(() =>
  ReactDOM.render(
    <React.StrictMode>
      <Suspense fallback={<Loading />}>
        <App />
      </Suspense>
    </React.StrictMode>,
    document.getElementById('root')
  )
)

i18next.js

import i18n from 'i18next'
import { initReactI18next } from 'react-i18next'

import Backend from 'i18next-http-backend'
import LanguageDetector from 'i18next-browser-languagedetector'
// not like to use this?
// have a look at the Quick start guide
// for passing in lng and translations on init

const Languages = ['en', 'fr']

i18n
  .use(Backend)
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    debug: true,
    whitelist: Languages,
    keySeparator: false,
    defaultNS: 'translation',
    ns: ['translation'],
    backend: {
      loadPath: `/locales/{{lng}}/{{ns}}.json`,
    },
    load: 'unspecific',
    react: {
      wait: true,
    },    
    interpolation: {
      escapeValue: false,
    },
  })

export default i18n

控制台 enter image description here

所以,这是要点。我在组件中使用了useTranslation钩子,它在localhost中工作得很好。但是,我一直在部署构建的生产环境中不断遇到missingKey错误。从其他答案尝试了所有可行的设置,但均未成功。抱歉,我想透彻一点。

1 个答案:

答案 0 :(得分:0)

找出解决方案。因为我是serving the build in a sub-directory,所以必须将其附加到loadPath

.env

REACT_APP_VERSION=$npm_package_version
REACT_APP_PUBLIC_URL='/dy/'

i18next.js

backend: {
  loadPath: `${process.env.PUBLIC_URL}/locales/{{lng}}/{{ns}}.json`,
}