Here's a summary of adding the I18n functionality.
You can refer to react-webpack-rails-tutorial and PR #340 for a complete example.
- Add
react-intl
&intl
toclient/package.json
, and remember tobundle && npm install
.
"dependencies": {
...
"intl": "^1.2.5",
"react-intl": "^2.1.5",
...
}
- In
client/webpack.client.base.config.js
, setreact-intl
as an entry point.
module.exports = {
...
entry: {
...
vendor: [
...
'react-intl',
],
...
react-intl
requires locale files in json format. React on Rails will help you to generate or updatetranslations.js
&default.js
automatically after you configured the following settings.
translations.js
: All your locales in json format.
default.js
: Default settings in json format.You can add them to
.gitignore
and.eslintignore
.
Update settings in config/initializers/react_on_rails.rb
to what you need:
# Replace the following line to the location where you keep translation.js & default.js.
config.i18n_dir = Rails.root.join("PATH_TO", "YOUR_JS_I18N_FOLDER")
- Javascript locale files must be generated before
npm build
.
To ensure this:
For test and production, add pre-hook
into client/package.json
to invoke build-in rake task.
{
...
"scripts": {
...
// Assuem that the following three lines are your original build script.
"build:test": "webpack --config webpack.config.js",
"build:production": "NODE_ENV=production webpack --config webpack.config.js",
// You need to add pre-hook for them.
"prebuild:test": "rake react_on_rails:locale",
"prebuild:production": "rake react_on_rails:locale",
...
}
}
For dev, add bundle exec rake react_on_rails:locale
to Procfile.dev
before npm build
.
client: sh -c 'rm app/assets/webpack/* || true && bundle exec rake react_on_rails:locale && cd client && npm run build:development'
- In React, you need to initialize
react-intl
, and set parameters for it.
...
import { addLocaleData } from 'react-intl';
import en from 'react-intl/locale-data/en';
import de from 'react-intl/locale-data/de';
import { translations } from 'path_to/i18n/translations';
import { defaultLocale } from 'path_to/i18n/default';
...
// Initizalize all locales for react-intl.
addLocaleData([...en, ...de]);
...
// set locale and messages for IntlProvider.
const locale = method_to_get_current_locale() || defaultLocale;
const messages = translations[locale];
...
return (
<IntlProvider locale={locale} key={locale} messages={messages}>
<CommentScreen {...{ actions, data }} />
</IntlProvider>
)
// In your component.
import { defaultMessages } from 'path_to/i18n/default';
...
return (
{ formatMessage(defaultMessages.yourLocaleKeyInCamelCase) }
)