Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My project is using i18next and react-i18next with success so far. No localize or server side involved.

Current setup:
- default & fallback language: en
- additional language: fr

I wanted to automate some things related to error checking:
1. Check that all key are translated in each defined language file
2. Either warn in dev env or lint for the ci/cd.

I've tried doing 1. with the following option:


    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,
    }

I thought if I deleted a key from my French .json (to test that it works) it will be logged, but it did not, only if I delete both key.

Other solution tried:
1. "eslint-plugin-i18n-json" but it doesn't check what I needed, haven't found the right options/config
2. Option 2.

Do you have any link or solution to help? (except those involving a saas)

like image 410
Hugo Gresse Avatar asked Oct 28 '22 00:10

Hugo Gresse


1 Answers

While @tudor answer work for eslint in javascript format, it wasn't in .json format. Here is the solution:

Plugin: eslint-plugin-i18n-json
Usage:

  1. Add the plugin to .eslintrc
    "extends": ["eslint:recommended", "plugin:i18n-json/recommended"],

  2. Add a new rules to .eslintrc that should contain all the required keys

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

    Note: For the require we need to go back 4 folders (from node_modules/eslint-plugin-i18n-json/src/util/require-no-cache.js) in order to get to our translation file.
    Since require will first try to resolve from the predefined __dirname. And the __dirname for require-no-cache.js is going to be ` node_modules/eslint-plugin-i18n-json/src/util.

  3. Add a new script to your package.json where it will check if all the key are existing (against the file from 2.)

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

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

like image 65
Hugo Gresse Avatar answered Nov 15 '22 12:11

Hugo Gresse