Closed rrlevy closed 5 years ago
I completely agree that this use-case is legitimate, ~probably~ documented in i18next's documentation and not having a proper solution to it is problematic. However I'm not really convinced it is a good idea to try to solve it using comment hints as I think it would quickly get overly convoluted and complicated (both for maintenance and usage). How would namespaces, plurals or contexts be usable in such scenario? I would feel uncomfortable introducing new special syntax for those "virtual" keys.
Even so, I reckon contexts are actually a very clean solution to this. If I'm not mistaken, it's their exact purpose:
// i18next-extract-mark-context-next-line ["", "404", "500"]
console.log(t("error", { context: code.toString() }));
{
"error": "Unknown error",
"error_404": "File not found",
"error_500": "Server error"
}
One minor issue is that you would have to slightly adapt your translation file and that you'll need to enable contexts (which may not always be the case). Do you see other downsides?
Another idea (I don't like much TBH) would be to add those "virtual translations" to dummy files that we would force Babel to pass on somehow. That would probably lead us to add a new option such as "dummyTranslationFiles": "src/**/*.translation.js"
. Those dummy translation files wouldn't be part of the final build when using a proper module resolver anyway (because they wouldn't be imported anywhere).
Lastly, one long-term alternative solution could also be to expose a plugin interface, so that anyone could add any key they like using whatever source they want.
I'm marking this issue as "documentation" as it needs a paragraph in FAQ at very least.
I like your suggestion of using contexts! It might solve all the issues we are currently having.
I suggest adding a comment hint to "force" adding a key to the extraction.
Ex: // i18next-extract-add-key key_name
Why it is important:
When using dynamic keys like
t(`error.${code}\`)
, you must disable the line with// i18next-extract-disable-next-line
or similar.However, if you want to add the keys of the multiple options that will be dinamically accessed at runtime, your only option would be to directly add them to the final json files.
As we regularly use
"discardOldKeys": true
on the configuration, it is not possible for us to add keys that will not be removed by babel-plugin-i18next-extract.Using the example of
t(`error.${code}`)
we would need to have in the translation.json file:{ "error": { "404": "File not found", "500": "Server error" } }
This could be added in the following manner: