[React Intl] Use Webpack to Conditionally Include an Intl Polyfill for Older Browsers

Some browsers, such as Safari < 10 & IE < 11, do not support the JavaScript Internationalization API, which react-intl depends on. In order to support these browsers, we’ll conditionally include an Intl polyfill using webpack require.ensure. This ensures only browsers that need the polyfill incur the extra load.

if (!window.Intl) {
  require.ensure([
    'intl',
    'intl/locale-data/jsonp/en.js',
    'intl/locale-data/jsonp/fr.js',
    'intl/locale-data/jsonp/es.js'
  ], (require) => {
    require('intl');
    require('intl/locale-data/jsonp/en.js');
    require('intl/locale-data/jsonp/fr.js');
    require('intl/locale-data/jsonp/es.js');

    runApp();
  })
} else {
  runApp();
}

function runApp() {
  addLocaleData([...en, ...fr, ...es]);

  let locale = (navigator.languages && navigator.languages[0])
    || navigator.language
    || navigator.userLanguage
    || 'en-US';

  ReactDOM.render(
    <IntlProvider locale={locale} messages={flattenMessages(messages[locale])}>
      <App />
    </IntlProvider>,
    document.getElementById('root')
  );
}

 

posted @ 2017-07-31 21:43  Zhentiw  阅读(419)  评论(0)    收藏  举报