On Rails 5, webpacker and I18n-js

Standard

So, webpacker is landing for Rails 5 (and will be part of Rails 5.1 core), which is really exciting news for frontend development with Rails backend.

I am building a project which heavily relies on I18n and multiple languages.
Assuming you know how to I18n your rails project, you’d need to use the yml files also on your react frontend.
This is how I have solved the I18n for Javascript and React:

First install I18n-js, with

yarn add i18n-js

Next, I have exposed my Rails locale to javascript globally by adding to application.html.erb (or any of your layout files). Inside script tag:

window.locale = '<%= I18n.locale.to_s %>'

(now on javascript console, you could check with locale or windows.locale)

Next, I needed to be able to read the translation yml file, so I have installed the yaml and json loader via:

yarn add yaml-loader json-loader

To configure them I have created a loader file in config/webpack/loaders/yaml.js which looks like:

module.exports = {
 test: /\.ya?ml$/,
 loaders: ['json-loader', 'yaml-loader']
}

this will enable me to read from yaml files.

Now I want to add to my react app, I18n and load the translations.
I have created a translations.js file in my components directory:

import I18n from "i18n-js";
import { en } from "../../../config/locales/en.yml";
import { pirate } from "../../../config/locales/pirate.yml";

I18n.locale = window.locale;
I18n.translations = { 'en': en, 'pirate': pirate }

export default I18n;

And boom I have I18n all ready for my react app.

On each component I import the translations with import I18n from './translations';
and when I need translated text I simply use { I18n.t('hello') }