Help wanted Using react-intl
Note from Maintainers
Please try the solution in https://github.com/facebookincubator/create-react-app/issues/1227#issuecomment-297604621 and let us know if it works well for you.
Hi all,
I'm following this tutorial https://medium.freecodecamp.com/internationalization-in-react-7264738274a0#.pgfd03878 to use internationalization in my app. Apparently the integreation is done by modifying the .babelrc file but to do so I have to eject, and I prefer not to. Is there any way to use React-Intl without ejecting create-react-app?
You only need the Babel plugin to generate the translate files which you can do as part of your production build without ejecting although it's a little messy. I'll post how later.
You can just install the required dependencies, add your own .babelrc, and add your "script": "translation" to your package.json.
E.g.:
npm install --save react-intl
npm install --save-dev babel-cli babel-preset-react-app babel-plugin-react-intl
add to the root folder:
{
"presets": ["react-app"],
"plugins": [
[
"react-intl", {
"messagesDir": "translations/messages",
"enforceDescriptions": false
}
]
]
}
then add to your package.json's "scripts" this line:
"translate": "NODE_ENV=production babel ./src >/dev/null"
You should be able to run both npm start/npm run build for running/building the project, and npm run translate for generating the translations.
@EnoahNetzach thanks for the answer!
How does : "NODE_ENV=production babel ./src >/dev/null" generate the translation? How does it work exactly?
Thank you 🙏
hi,
Internationlization is a pretty important feature for mobile apps these days. Could we have react-intl inbuilt in the create-react flow?
Regards Arsh
@firaskrichi it works as intended by react-intl, by using babel's AST to catch translations and replace them (I suggest you to look it up, it's really interesting, if you like to know how exactly it - and in general babel plugins - works!).
The > /dev/null part is there simply to discharge the babel parsed output.
Moreover what I suggested is simply what the official doc tells to do ;)
@arshmakker being that it's easily pluggable, not everybody wants to use i18n, and the specific tool (format.js) is not that reliable if you want to do substantial i18n (@see), I'm not sure at all it would be possible.
This is a really useful discussion and the information provided by @EnoahNetzach has really helped get react-intl into my create-react-app application. I think it would be exceptionally valuable to have i18n working out-of-the-box with create-react-app (or at least some good documentation explaining how to use it).
The main thing that I don't quite understand is how this works with a production build. I've followed the various scripts to combine individual component message files into a single JSON file for the default locale, I've then added a different locale (with translated messages) and updated the IntlProvider locale to be the new locale.
When you use npm run build the new locale translations are lost (probably because the translate scripts provided by the blogs combine the component messages into locale files in the build directory).
If anyone can shed any light on the correct approach to combining the information provided so far in a production story I'd be very grateful.
@draperd, as a non English native speaker, I find that unfortunately no i18n instrument in js is a "catch all" solution. I've used a couple and always ended up tweaking them to my needs (e.g. subject/direct object gender and numerosity, probably @gaearon could say something about Russian desinences, I don't know if there is someone from Iceland here, and so on and so forth..). Whichever translation package we could add, it's going to solve only a limited set of cases and needs, so I'm against adding them in altogether, specially when the integration is not "that" painful.
@EnoahNetzach Thanks for your response... I wasn't suggesting that there is a one-size fits all solution, but it would seem that React-Intl is a pretty good fit. I can understand the rationale of not wanting to tie "create-react-app" to a single solution, however a solution of some kind is almost going to be required. Any serious application is going to want to support i18n so I'm simply suggesting that either something is provided by default, or that documentation is provided to assist people in achieving a solution.
The information you have previously provided has been invaluable but only as far as the development experience goes. My point is that when I'm ready to ship my finished application I need translation to work in production for multiple locales and I've not been able to find that information anywhere so far.
I'll continue to experiment and hopefully find a working solution which I'll then write up, I was just hoping that someone may have already encountered and solved this problem using react-intl.
Just to follow up my previous comment... what I actually need is a per component solution which I've now managed to achieve using the higher order component pattern. I will write this solution up as soon as I can for anyone that comes across this thread as it might be useful.
@draperd good!
As promised... hopefully this might be of use to some people: https://medium.com/@dave.draper20/i18n-per-component-in-react-using-the-higher-order-component-pattern-b04f32e7cd6a#.ewrplesd7
For everyone that the suggestion from @EnoahNetzach is not working out of the box I had to put following in my package.json, probably as I'm working on windows
"translate": "cross-env NODE_ENV=production ./node_modules/.bin/babel ./src > NUL",
Yep, env var definition and the output indirection to /dev/null work only in Linux/Mac.
cross-env solves the first part, for the second sincerely I have no idea how to accomplish that on Windows..
If you don't want to have to npm install --save-dev babel-cli or create the babel.rc file, or worry about issues on Windows, you can use the babel API:
// scripts/translate.js
process.env.NODE_ENV = 'development';
const fs = require('fs');
const path = require('path');
const globSync = require('glob').sync;
const mkdirpSync = require('mkdirp').sync;
const transformFileSync = require('babel-core').transformFileSync;
const paths = require('../config/paths');
//////////////////////////////
// Add to `/config/paths.js`:
// appBuildMessages: .. where to output the messages
//////////////////////////////
globSync(path.join(paths.appSrc, '/**/*.js'))
.map((filename) => {
const result = transformFileSync(filename, {
plugins: ['react-intl']
});
const messages = result.metadata["react-intl"]["messages"];
if (messages.length > 0) {
const relFn = path.relative(paths.appSrc, filename);
const outFilename = path.join(
paths.appBuildMessages,
path.dirname(relFn), `${path.basename(relFn, ".js")}.json`);
mkdirpSync(path.dirname(outFilename));
const outFd = fs.openSync(outFilename, 'w');
fs.write(outFd, JSON.stringify(messages));
}
});
...
"scripts": {
...,
"translate": "node scripts/translate.js",
}
I tried the .bablerc solution, but it does not work unless and untill i do an eject, is that just me?
@EnoahNetzach I tried your solution of using a translate script, but I wound up with a "missing script: translate" error. I don't know if this means your solution is no longer valid with the latest version of CRA, or if I have missed a detail.
In my package.json file, I have:
"scripts": {
"translate": "NODE_ENV=production babel ./src >/dev/null"
},
...and am running react 15.5.4, react-scripts 0.9.5, babel-cli 6.24.1, babel-plugin-react-intl 2.3.1, and babel-preset-react-app 2.2.0. My .babelrc sits at the root of my project folder, and is verbatim what you posted above:
{
"presets": ["react-app"],
"plugins": [
[
"react-intl", {
"messagesDir": "translations/messages",
"enforceDescriptions": false
}
]
]
}
...and then here's the CLI:

Have I missed something obvious?
@cwalv question about your solution: it appears that you're outputting a separate .json file for each .js file in which you find translatable content (if I'm reading your code right). Is there a reason for doing that as opposed to putting all translatable content into a single .json file? I'm just getting into i18n, so I don't know if you're following an accepted practice, or if that's just a personal preference on your part.
Thanks!
@bmueller-sykes, you're right, I only put in half the script. I adapted it from https://github.com/yahoo/react-intl/blob/b82a899a59c762fcc590e1fa824b87da6ad409d9/examples/translations/scripts/translate.js, which adds this to the .babelrc file:
"plugins": [
["react-intl", {
"messagesDir": "./build/messages/"
}]
which creates the .json files when babel runs, similar to how my snippet above does, and then the translate script has a second pass that aggregates separate files into one:
// Aggregates the default messages that were extracted from the example app's
// React components via the React Intl Babel plugin. An error will be thrown if
// there are messages in different components that use the same `id`. The result
// is a flat collection of `id: message` pairs for the app's default locale.
const messagesGlob = path.join(paths.appBuildMessages, '**', '*.json');
let defaultMessages = globSync(messagesGlob)
.map((filename) => fs.readFileSync(filename, 'utf8'))
.map((file) => JSON.parse(file))
.reduce((collection, descriptors) => {
descriptors.forEach(({ id, defaultMessage }) => {
if (collection.hasOwnProperty(id)) {
throw new Error(`Duplicate message id: ${id}`);
}
collection[id] = defaultMessage;
});
return collection;
}, {});
// For the purpose of this example a fake locale: `en-UPPER` is created and
// the app's default messages are "translated" into this new "locale" by simply
// UPPERCASING all of the message text. For a real translation this would mean some
// offline process to get the app's messages translated by machine or
// professional translators.
let uppercaseTranslator = new Translator((text) => text.toUpperCase());
let uppercaseMessages = Object.keys(defaultMessages)
.map((id) => [id, defaultMessages[id]])
.reduce((collection, [id, defaultMessage]) => {
collection[id] = uppercaseTranslator.translate(defaultMessage);
return collection;
}, {});
mkdirpSync(LANG_DIR);
fs.writeFileSync(LANG_DIR + 'en-US.json', JSON.stringify(defaultMessages, null, 2));
fs.writeFileSync(LANG_DIR + 'en-UPPER.json', JSON.stringify(uppercaseMessages, null, 2));
I released a workaround solution to NPM react-intl-cra, so that you can simply extract messages of CRA-project from the command line.
$ yarn add react-intl-cra --dev
$ react-intl-cra './src/**/*.js' -o messages.json
Thanks @evenchange4 , that npm package really helped my case.
I was struggling with intl after shifting to react-scripts.
REgards ARsh