i18next best practice i18next best practice json json

i18next best practice


Maybe I'm missing something here but couldn't you simply do this:

if (userLanguage != 'en') {    i18n.init({        lng                 : userLanguage,        shortcutFunction    : 'defaultValue',        fallbackLng         : false,        load                : 'unspecific',        resGetPath          : 'locales/__lng__/__ns__.json'    });}

That way your script i18n wouldn't be initialized unless you actually needed the translation service.


i18next-parser author here, I will explain how I use i18next and hopefully it will help:

1/ I do not use defaultTranslation in the code. The reason is that it doesn't belong in the code. I understand the benefit of having the actual text but the code can get bloated quickly. The difficult part consists in defining intelligible translation keys. If you do that, you don't really need the defaultTranslation text anymore. The translation keys are self-explainatory.

2/ If you have a 404 on the /locales/en/translation.json, then probably that you don't have the file in your public directory or something similar. With gulp you can have multiple destination and do dest('locales').dest('public/locales') for instance.

3/ If there is no translation in the catalog, make sure you run the gulp task first. Regarding populating the catalog with the defaultTranslation you have, it is a tricky problem to solve with regexes. Think of this case <div data-i18n="key">Default <div>translation</div></div>. It needs to be able to parse the inner html and extract all the content. I just never took the time to implement it as I don't use it.


See http://i18next.com/pages/doc_init.html under "whitelist languages to be allowed on init" (can't fragment link on those docs...):

i18n.init({ lngWhitelist: ['de-DE', 'de', 'fr'] });

Only specified languages will be allowed to load.

That should solve your problem. Though I suppose a blacklist would be even better.