gilbsgilbs / babel-plugin-i18next-extract

Babel plugin that statically extracts i18next and react-i18next translation keys.
https://i18next-extract.netlify.com
MIT License
161 stars 37 forks source link

Use constants as keys #109

Closed woodreamz closed 4 years ago

woodreamz commented 4 years ago

Describe the bug

Hi,

I think it is more a question than a bug. I installed then plugin and it is working well. In my case, I work on a big project and we use constants for i18n keys.

How to reproduce

I Have a file constants.js containing: const COMMON = { save: 'common-save', cancel: 'common-cancel', }

In my app.js, I do: t(COMMON.save);

I get the error "Couldn't evaluate i18next key. You should either make the key evaluable or skip the line using a skip comment...".

If I use t('common-save'), it works fine.

Babel configuration:

"babel": { "presets": [ "react-app" ], "plugins": [ "@babel/plugin-proposal-optional-chaining", [ "@babel/plugin-proposal-decorators", { "legacy": true } ], "syntax-dynamic-import", [ "babel-plugin-styled-components", { "ssr": false, "displayName": true, "fileName": false, "minify": true, "pure": false, "transpileTemplateLiterals": false } ], "lodash", "inline-react-svg", [ "i18next-extract", { "nsSeparator": "-", "keySeparator": ".", "outputPath": "public/locales/{{locale}}/{{ns}}.json" } ] ] }

Expected behavior

I expect to the plugin is able to resolve constants. Is it a way to use constants with the plugin? (without adding a comments everywhere).

Your environment

Thanks! Good work for this plugin!

gilbsgilbs commented 4 years ago

Hi,

Thanks for the report.

The FAQ already mentions that this is not supported and probably never will, but feel free to submit a PR if you think this isn't clear enough.

This is a babel plugin, therefore it can only perform static analysis. Resolving variables or symbols across modules might be doable in some very simple cases, yet babel is definitely not a good fit for such scenario. It might be possible, but it would add so much complexity and maintenance burden and hacks that it wouldn't be worth it.

I'm afraid you'll have to move away from variable keys if you want to use a static tool. Sorry. By the way, I don't think comment hints would be of any help in this case.

woodreamz commented 4 years ago

Thank you for the quick answer!

barrymichaeldoyle commented 3 years ago

Just for future reference if anyone comes across this. The way to work with this is to translate it inside your constants.js file.

Like this:

const COMMON = { save: t('common-save'), cancel: t('common-cancel'), }

Then in your App.js you can simple write: COMMON.save