i18next is a popular internationalization JavaScript library.
One thing to remember when you work with it, is that languages’ names are case sensitive.
The case of a language you pass to the i18next’s init
function and the case of a language in your resources should be the same. Otherwise your translations won’t work correctly.
For example, the code below won’t work as expected, as the case of the language "en"
in resources and "EN"
in init
function do not math. i18next will return the key name (i.e. "helloKey"
) instead of the correct translation (i.e. "hello world"
):
const resources = {
en: {
translation: {
"helloKey": "hello world"
}
}
};
i18next.init({
lng: 'EN',
resources: resources
}, (err, t) => {
// This will NOT work as expected.
// "en" in resources and "EN" in init function do not match
// helloWorld = "helloKey" and not "hello world".
const helloWorld = i18next.t("helloKey");
});
Note: This applies to all resources elements: not only languages, but namespaces and keys as well.
This is specially important when you get the language context from the environment and not setting it directly. Let assume that you have got a 3rd party environment that provides your code with the correct locale:
// Get the language from the custom environment
// We don't know the case of the language here:
// could be "en", "En", "EN", etc.
let environmentLanguage = Custom_System.context.displayLanguage;
i18next.init({
lng: environmentLanguage,
resources: resources
});
The advice here is to stick to a particular notation with your resource files.
For example:
1. Always use lowercase for languages in your resource files.
2. Before setting a language in i18next make it lowercase to make sure that it matches your resource.
Happy Coding!