Introduction
This is a simple i18next backend to be used in the browser. It will load resources from a backend server using the fetch API.
Getting started
This backend is most useful when XMLHttpRequest
is not available, such as with Service Worker contexts. It is also useful when support for older browsers is not a concern, and newer APIs are a priority.
Source can be loaded via npm.
# npm package
$ npm install --save i18next-fetch-backend
Wiring up:
import i18next from 'i18next';
import Fetch from 'i18next-fetch-backend';
i18next
.use(Fetch)
.init(i18nextOptions);
- As with all modules you can either pass the constructor function (class) to the i18next.use or a concrete instance.
Backend Options
{
loadPath: '/locales/{{lng}}/{{ns}}.json',
parse: function(data) { return data.replace(/a/g, ''); },
addPath: 'locales/add/{{lng}}/{{ns}}',
stringify: JSON.stringify,
allowMultiLoading: false,
multiSeparator: '+',
requestOptions: {
mode: 'cors',
credentials: 'same-origin',
cache: 'default',
},
fetch: function (url, options, callback) {},
}
Options can be passed in:
preferred - by setting options.backend in i18next.init:
import i18next from 'i18next';
import Fetch from 'i18next-fetch-backend';
i18next
.use(Fetch)
.init({
backend: options
});
on construction:
import Fetch from 'i18next-fetch-backend';
const fetch = new Fetch(null, options);
via calling init:
import Fetch from 'i18next-fetch-backend';
const fetch = new Fetch();
fetch.init(options);
Service Worker example
import i18next from 'i18next';
import Fetch from 'i18next-fetch-backend';
let t = null;
self.addEventListener('activate', (event) => {
event.waitUntil(new Promise((resolve, reject) => {
i18next
.use(Fetch)
.init({
fallbackLng: ['ja', 'en', 'zh'],
preload: ['ja', 'en', 'zh'],
ns: 'translation',
defaultNS: 'translation',
keySeparator: false,
nsSeparator: false,
backend: {
loadPath: '/locales/{{lng}}/{{ns}}.json',
},
}, (err, _t) => {
if (err) {
reject(err);
return;
}
t = _t;
resolve();
});
}));
});