问题
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?
回答1:
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.
回答2:
Hey I have done this now, as described below and its working :-)
const possibleLocale = navigator.language.split('-')[0] || 'en';
addLocaleData(require(`react-intl/locale-data/${possibleLocale}`));
Here, the locale is fetched from the browser through navigator.language. Hope this helps :-)
来源:https://stackoverflow.com/questions/41282510/how-to-add-locale-data-dynamically-using-react-intl