kitimenpolku
kitimenpolku

Reputation: 2604

babel-plugin-i18next-extract - Extract translation keys outside react component

Im using i18next, react-i18next and babel-plugin-i18next-extract.

I have a "large" static json object. This json object has static keys that match translation keys.

// file: professions.js
//
// Large array with static objects
export default [
  { profession: 'translation.profession.teacher' },
  ...
  { profession: 'translation.profession.astronaut' },
];

While the following code displays the translations properly, the extraction of the keys does not work.

import { useTranslation } from 'react-i18next';
import professions from'../data/professions.json';

function SelectProfessionComponent(){
  const { t } = useTranslation();
  return (
    <select>
    { professions.map( {profession} => {
      <option>{t(profession)}</option>
    })}
    </select>
  )
}

How could I make babel-plugin-i18next-extract to recognized 'translation.profession.teacher', 'translation.profession.teacher' and others as translation keys from file professions.json?

Upvotes: 1

Views: 1229

Answers (1)

kitimenpolku
kitimenpolku

Reputation: 2604

I found out a way to do it (maybe hacky, maybe not).

First, we do an idempotent function that returns what it receives.

// file: extractKey.js
export function eK(key) { return key;}

From the static data, we mark those that are acting as translation keys by using the eK function defined above:

// file: professions.js
//
// Large array with static objects
import { eK } from '../extractKey';

export default [
  { profession: eK('translation.profession.teacher') },
  ...
  { profession: eK('translation.profession.astronaut') },
];

And configure babel-plugin-i18next-extract to detect the function name eK:

// babel-plugin-i18next-extract config
{
  "tFunctionNames": ["t", "eK"]
}

That's all. Hope this helps to someone else.

Upvotes: 1

Related Questions