Config react-i18next to load locales from bundle in webpack.

Config react-i18next to load locales from bundle in webpack.

2016, Jul 24    

#react-i18next

npm install react-i18next i18next-browser-languagedetector i18next-xhr-backend --save

#Loader

npm install json-loader bundler-loader --save-dev

#webpack config

var jsonLoader = { test: /\.json$/, loader: 'json' }

config.module.loaders.push(jsonLoader, /*...other loaders*/);
app.js or the entry js where add i18n initialization
function loadLocales(url, options, callback, data) {
  try {
    let waitForLocale = require('bundle!./locales/'+url+'.json');
    waitForLocale((locale) => {
      callback(locale, {status: '200'});
    })
  } catch (e) {
    callback(null, {status: '404'});
  }
}

#react app.js

i18next
  .use(XHR)
  .init({
    backend: {
      loadPath: '',
      parse: (data) => data,
      ajax: loadLocales
    }
  }, (err, t) => {
    // ...
  });