ttag-org / ttag

:orange_book: simple approach for javascript localization
https://ttag.js.org/
MIT License
344 stars 43 forks source link

Getting error while using var as an argument for gettext #247

Closed Sk92 closed 11 months ago

Sk92 commented 2 years ago

Hey! I'm struggling with an issue. I need to group my localized strings in a JS object and then use them calling the gettext function.

The code works great but when I try to extract strings using the command ttag update I get a BABEL_TRANSFORM_ERROR saying You can not use MemberExpression 'localizedStrings.string1' as an argument to gettext.

I don't know if the issue is related to this project or to @ttag-org/babel-plugin.

HOW TO REPRODUCE THE ISSUE

Here you can find a sample project with the scenario described above: https://codesandbox.io/s/ttag-issue-1cnk79?file=/src/App.tsx

As you can see, selecting the Italian language the localized string changes properly.

Unfortunately, when you try to update to .po file you would get the BABEL_TRANSFORM_ERROR.

Steps to get the error:

  1. Download the project from CodeSandbox
  2. Run: npm install
  3. Run: npx ttag update src/i18n/it.po src/
  4. BABEL_TRANSFORM_ERROR raised
AlexMost commented 11 months ago

Hey, sorry for the late reply. That is the expected behavior and how babel plugin is designed to work with translations in .po files. When you are trying to extract something like gettext(member.expression) what should the translator translate in the .po file, variable name?

Probably you should place gettext call inside your object with translations like

const localizedStrings = {
  string1: gettext('string to be extracted and is visible for the translator')
}

Hope that will help.

AlexMost commented 11 months ago

Here is the working code for your example - https://codesandbox.io/s/ttag-issue-forked-66q9hr?file=/src/App.tsx:163-189

Also maybe there is no reason to create one god object for the translations, you can use tThis is a localized string`` just inside your jsx. Here is the modified preffered version - https://codesandbox.io/s/ttag-issue-forked-mn9vl2