Automatically converts a React codebase to support i18n using the format.js API
Installation:
npm install -g auto-i18n-react
Usage:
auto-i18n-react --target path/to/target/directory
This will target all files (with extensions .jsx by default) and transform them in place.
This:
import React from 'react';
class ShoppingList extends React.Component {
render() {
return (
<div className='shopping-list' title="International Shoppy List">
<h1>International Shopping List</h1>
<ul>
<li>Mexican food</li>
<li>German food</li>
<li>American food</li>
</ul>
</div>
);
}
}
export default ShoppingList;
becomes:
import { FormattedMessage, injectIntl } from 'react-intl';
import React from 'react';
class ShoppingList extends React.Component {
render() {
var intl = this.props.intl;
return (
<div
className='shopping-list'
title={intl.formatMessage({
defaultMessage: 'International Shoppy List'
})}
>
<h1>
<FormattedMessage defaultMessage='International Shopping List' />
</h1>
<ul>
<li>
<FormattedMessage defaultMessage='Mexican food' />
</li>
<li>
<FormattedMessage defaultMessage='German food' />
</li>
<li>
<FormattedMessage defaultMessage='American food' />
</li>
</ul>
</div>
);
}
}
export default injectIntl(ShoppingList);
For file extensions other than jsx simply target them with the --ext option:
auto-i18n-react -target target/path --ext jsx --ext js
Full option list:
auto-i18n-react --help
Options:
--help Show help [boolean]
--version Show version number [boolean]
--target, -t Target directory where files will be converted in place [string]
--ext, -e Extensions to target [array] [default: ["jsx"]]
The algorithm is a bit aggressive so it's possible that there were some false positives but those are pretty easy to find once you have the translation file (generated by formatjs extract
). It will not handle more complicated things like pluralization or rich text formatting. Those are edge cases that will need to be handled manually.
It also works with functional components that use hooks and is safe to re-run multiple times on the same file (if you later add more things that need to be i18n'ed).