How to add locale data dynamically using React Intl?

Santhosh picture Santhosh · Dec 22, 2016 · Viewed 8.3k times · Source

Am using React-intl for internationalization of an UI Util Library. The library has a folder say i18n wherein I place json files for different locales.If the user of this library want to add support for additional locales, he/she can place additional json file with key/value pairs for the respective locale.

But React-intl requires to import and addLocaleData for the respective locale in prior.For example,

import fr from 'react-intl/locale-data/fr';
addLocaleData([...fr]);

Is there a way to addLocaleData and import the locale library for the respective locale dynamically in React-intl?

Answer

slchap5 picture slchap5 · Dec 22, 2016

If you are using webpack. You can code-split the different locale data from your app and load dynamically. Webpack 1 supports only require.ensure() and webpack 2 also supports System.import(). System.import returns a promise while require.ensure uses a callback. https://webpack.github.io/docs/code-splitting.html

With System.import()

import { addLocaleData } from 'react-intl';

const reactIntlLocaleData = {
  fr: () => System.import('react-intl/locale-data/fr'),
  en: () => System.import('react-intl/locale-data/en')
};

function loadLocaleData(locale){
  reactIntlLocaleData[locale]()
  .then((intlData) => {
    addLocaleData(intlData)
  }
}

With require.ensure()

import { addLocaleData } from 'react-intl';

const reactIntlLocaleData = {
  fr: () => require.ensure([], (require) => {
    const frData = require('react-intl/locale-data/fr');
    addLocaleData(frData);
  }),
  en: () => require.ensure([], (require) => {
    const enData = require('react-intl/locale-data/en');
    addLocaleData(enData);
  })
};

function loadLocaleData(locale){
  reactIntlLocaleData[locale]();
}

Depending on your development environment the code above may or may not work. It assumes you are using Webpack2 along with Babel to transpile your code.