Search code examples
reactjstypescriptinternationalizationreact-intlbabel-plugin-react-intl

i18n message extraction in CRA using TypeScript


I'm trying to get i18n message extracted (defined by react-intl's defineMessages) to work properly in a CRA using TypeScript.
I've got an existing react app bootstrapped by CRA with a couple of hundrets of lines of code. So rewriting the application w/o TypeScript isn't an option.


Here's what i've tried so far:

First Attempt

Following this guide in order to get it to work.
When closely following the guide (although react-intl-cra is deprecated) the language files will generate properly.
However if you create the app using create-react-app react-intl-example --typescript and change the script to

"extract:messages": "react-intl-cra 'src/**/*.{js,jsx,ts,tsx}' -o 'src/i18n/messages/messages.json'"

it will break with a compiler error.

Second Attempt

Since react-intl-cra was refering to a react-app-rewired solution, I've tried adding it alongside customize-cra and babel-plugin-react-intl to a freshly generated CRA (using TS). However no luck there as well and after some short period of research I found that it's officially not supported.

Third attempt:

Adding extract-react-intl-messages to my project and running:

$ npx extract-messages -l=en,ja -o app/translations -d en --flat false 'src/**/!(*.test).tsx'

failed with an error as well.


I ran out of ideas, hence I came here to ask. From what I've seen TypeScript has been well advertised in the last couple of years and I don't think I have to justify that React is still pretty hyped. Moreover I can't imagine, that i18n is an uncommon concern in application development.
However I wasn't able to find any up-to-date guide or anything useful on npmjs.com.

TL;DR;

What I need:

  • Extract messages from defineMessages from react-intl into json files
  • Must work in a CRA using --typescript
  • Should not utilize npm run eject

What I've tried:


Solution

  • It's explained here: https://github.com/akameco/extract-react-intl-messages#typescript

    Basically you need to

    npm install --save-dev @babel/core @babel/preset-typescript @babel/preset-react

    and add

    @babel/preset-typescript

    to your .babelrc:

    {
        "presets": [
            "@babel/preset-react",
            "@babel/preset-typescript"
        ],
    }
    

    Then you can run

    npm run extract-messages 'src/**/*.[jt]sx'