i18next 在缺少语言键时发出警告或 lint(不是 fallbackLng)

i18next warn or lint on missing key for a language (not the fallbackLng)

到目前为止,我的项目正在使用 i18next 和 react-i18next 并取得成功。不涉及本地化或服务器端。

当前设置:
- 默认和后备语言:en
- 附加语言:fr

我想自动化一些与错误检查相关的事情:
1.检查每个定义的语言文件中的所有密钥是否已翻译
2. 在开发环境或 lint 中警告 ci/cd.

我已经尝试使用以下选项执行 1.:


    saveMissing: true,
    saveMissingTo:"all",
    missingKeyHandler: (ng, ns, key, fallbackValue) => {
        console.log(ng, ns, key, fallbackValue)
    },

    // other options
    resources: {
        en: {
            translations: enTranslation,
        },
        fr: {
            translations: frTranslation,
        },
    },
    fallbackLng: 'en',
    ns: ['translations'],
    defaultNS: 'translations',

    interpolation: {
        formatSeparator: ',',
    },

    react: {
        wait: true,
    }

我想如果我从我的法语 .json 中删除一个密钥(以测试它是否有效),它将被记录,但它没有,只有当我删除两个密钥时。

尝试过的其他解决方案:
1. "eslint-plugin-i18n-json" 但它没有检查我需要什么,还没有找到合适的 options/config
2. 选项 2.

您有任何 link 或解决方案可以帮助吗? (涉及saas的除外)

您可以使用 https://github.com/godaddy/eslint-plugin-i18n-json#i18n-jsonidentical-keys。方法如下:

将此添加到您的 eslintrc 中:

module.exports = {
  extends: ["plugin:i18n-json/recommended"],
  rules: {
    "i18n-json/identical-keys": [
      2,
      {
        filePath: path.resolve("translations/en.json")
      }
    ]
  }
};

然后 运行 eslint 使用此选项:

eslint --fix --ext .json --format node_modules/eslint-plugin-i18n-json/formatter.js translations/

这里假定包含翻译的文件夹名为 translations(您应该调整路径)。

这是一个代码和框,证明它有效:https://codesandbox.io/s/friendly-minsky-9siu4

您可以使用终端 运行 npm run lint 并且您可以使用 translations/en.jsontranslations/de.json 中的值来检查它是如何工作的。

虽然@tudor 以 javascript 格式回答 eslint,但它不是 .json 格式。 这是解决方案:

插件: eslint-plugin-i18n-json
用法

  1. 将插件添加到 .eslintrc
    "extends": ["eslint:recommended", "plugin:i18n-json/recommended"],

  2. 向 .eslintrc 添加新规则,其中应包含所有必需的键

    "rules": {
        "i18n-json/identical-keys": [2, {
            "filePath": {
                "admin.json": "../../../../src/languages/en.json",
            }
        }],
    }
    

    注: 对于这个要求,我们需要返回 4 个文件夹(来自 node_modules/eslint-plugin-i18n-json/src/util/require-no-cache.js)才能找到我们的翻译文件。
    由于 require 将首先尝试从预定义的 __dirname 中解析。而 require-no-cache.js 的 __dirname 将是` node_modules/eslint-plugin-i18n-json/src/util.

  3. 向您的 package.json 添加一个新脚本,它将检查所有密钥是否都存在(针对 2. 中的文件)

    script: {
        "lint:i18n": "eslint src/**/languages/*.json"
    }
    

来源:https://github.com/godaddy/eslint-plugin-i18n-json/issues/31#issuecomment-604636886

在我的用例中,我只是希望应用程序在特定环境中抛出错误。我在我的配置中添加了以下内容,它对我有用。

  saveMissing: true,
  missingKeyHandler: (ng, ns, key, fallbackValue) => {
    throw new Error(`Key not found ${key}, ${ng}, ${ns}, ${fallbackValue}`);
  },

希望对你有帮助

我对你的情况的假设,控制台日志语句不起作用,因为密钥存在于你的后备语言中。