react-i18next: When the key exists in en.json 我得到这个错误 -> i18next::translator: missingKey en translation

react-i18next: When the key exists in en.json I get this error -> i18next::translator: missingKey en translation

我遇到了很多这样的错误:

i18next::translator: missingKey en translation 

我的控制台截图:

这是 /locales/en.json 中的对象之一,表明这些键没有丢失。

  "template-manager": {
    "desktop-button": "Desktop",
    "header": "Custom Order Forms",
    "header-button": "New Order Form Template",
    "mobile-button": "Mobile",
    "preview-button": "Preview",
    "redo-button": "Redo",
    "tablet-button": "Tablet",
    "toggle-device-Frame": "Toggle Device Frame",
    "undo-button": "Undo"
  }

此错误并非发生在所有键上,只是其中一些。

我们正在使用一个脚本来为我们添加所有的键,其中 i18n 的文本被包装在 <trans> 标签中:

"updateLanguageKeys": "rm -rf public/locales/en.json && npx babel -f .babelrc 'src/**/*.{js,jsx}'",

.babelrc 的内容:

{
    "presets": [
        "@babel/preset-env",
        [
            "@babel/preset-react",
            {
                "runtime": "automatic"
            }
        ]
    ],
    "plugins": [
        [
            "i18next-extract",
            {
                "discardOldKeys": true,
                "outputPath": "public/locales/{{locale}}.json"
            }
        ],
        ["@babel/proposal-class-properties", { "loose": true }],
        ["@babel/proposal-private-methods", { "loose": true }],
        ["@babel/proposal-private-property-in-object", { "loose": true }],
        ["@babel/proposal-object-rest-spread", { "loose": true }]
    ]
}

设置如下:

i18n.use(detector)
    .use(backend)
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
        returnEmptyString: false,
        backend: { loadPath: process.env.LOCALES_PATH },
        whitelist: ['en', 'de', 'es', 'fr', 'it', 'pt'],
        fallbackLng: 'en', // use en if detected lng is not available
        debug: true, // Use this to see what's going on in console
        react: {
            useSuspense: false
        },
        interpolation: {
            escapeValue: false // react already safes from xss
        }
    })

原来是这里环境变量的问题

React 应用程序中的环境变量必须以 REACT_APP 开头,因此需要将其更改为 process.env.REACT_APP_LOCALES_PATH

i18n.use(detector)
    .use(backend)
    .use(initReactI18next) // passes i18n down to react-i18next
    .init({
        returnEmptyString: false,
        backend: { loadPath: process.env.REACT_APP_LOCALES_PATH }, // <--right there
        whitelist: ['en', 'de', 'es', 'fr', 'it', 'pt'],
        fallbackLng: 'en', // use en if detected lng is not available
        debug: true, // Use this to see what's going on in console
        react: {
            useSuspense: false
        },
        interpolation: {
            escapeValue: false // react already safes from xss
        }
    })