简体   繁体   中英

Using i18next in a webpack bundled application

I'm quite new to the webpack ecosystem so I don't grasp all of its concepts, but I'm working on an application which uses it. I'm trying to set up i18next (see: https://github.com/i18next/i18next ) and its XHR associated module ( https://github.com/i18next/i18next-xhr-backend ).

i18next fetch the translation files via XHR, so when the AJAX request is finished, i18next is initialized in the provided callback. Basically, I want this initialized i18next available through all my modules so I can translate strings anywhere.

There is a section about webpack on i18next-xhr-backend's github page, but I don't really understand how to structure the code and how to use it.

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'});
  }
}

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

I tried to turn this into a webpack plugin with no success, with the hope it would be available everywhere. But it might not be the right way to accomplish this task.

如果您想使用webpack捆绑翻译,则可以尝试https://github.com/atroo/i18next-resource-store-loader

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM