i18next
JavaScript i18n (Internationalization) Package: i18next learn once - translate everywhere, i18next is an internationalization-framework written in and for JavaScript. But it’s much more than that!
Categories:
Install
npm install i18next --save
yarn add i18next
Language json setting
Basic
import i18next from 'i18next';
i18next.init({
lng: 'en', // if you're using a language detector, do not define the lng option
debug: true,
resources: {
en: {
translation: {
"key": "hello world"
}
}
'zh_TW': {
translation: {
"key": "你好世界"
}
}
}
});
// hello world
console.log(i18next.t('key'));
// 你好世界
console.log(i18next.t('key', {lng: 'zh_TW'}));
// hello world
console.log(i18next.t('key', {lng: 'de'}));
Load languages from json file
Make use of i18next-fs-backend
AWS lambda, Google Cloud Functions, Azure Functions, etc…
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
const backend = new Backend({
// path where resources get loaded from
loadPath: '/locales/{{lng}}/{{ns}}.json'
});
i18next
.use(backend)
.init({
// initImmediate: false, // setting initImediate to false, will load the resources synchronously
...opts,
...yourOptions
}); // yourOptions should not include backendOptions!
import/require your language json files directly
import i18next from 'i18next';
import en from './locales/en.json'
import de from './locales/de.json'
i18next
.init({
...opts,
...yourOptions,
resources: {
en,
de
}
});
Fallback to different languages
// fallback to one language
i18next.init({
fallbackLng: 'en'
});
// fallback ordered
i18next.init({
fallbackLng: ['fr', 'en']
});
// fallback depending on user language
i18next.init({
fallbackLng: {
// Find language code => mapping exist language code
'de-CH': ['fr', 'it'], //French and Italian are also spoken in Switzerland
'zh-Hant': ['zh-Hans', 'en'],
'es': ['fr'],
'default': ['en']
}
});
Namespace fallback
i18next.init({
// files to load
ns: ['app', 'common'],
// default namespace (needs no prefix on calling t)
defaultNS: 'app',
// fallback, can be a string or an array of namespaces
fallbackNS: 'common'
}, () => {
i18next.t('title') // -> "i18next"
i18next.t('button.save') // -> "save" (fallback from common)
// without fallbackNS you would have to prefix namespace
// to access keys in that namespace
// and this is not recommended when used in combination with natural language keys
i18next.t('common:button.save') // -> "save"
// better use the ns option:
i18next.t('button.save', { ns: 'common' }) // -> "save"
});