A simple really small i18n library with intuitive API.
- Dependency free
- Really small
- Compatible with Web Components and LitElement
$ npm i @syu93/translit
import Translit from '@syu93/translit';
const i18n = new Translit({
translation: {
en: {
hello: {
world: 'Hello world'
},
itemInList: (count) => `This list contains ${count} item${count > 1 ? 's' : ''}.`
}
}
});
console.log(i18n.t('hello.world'))
// => Hello world
By default Translit define the locale as English en
.
You can change the locale in the constructor
import Translit from '@syu93/translit';
const i18n = new Translit({
translation: {
// ...
},
locale: 'en'
});
Or you can dynamically change the locale using the setLocale
method
i18n.setLocale('fr');
Or you can even set the locale as you use it
i18n.t('hello.wold', null, 'en');
You can as well load another locale with the addLocale
method
i18n.addLocale({
fr: {
hello : {
world: 'Bonjour à tous'
}
}
});
Define a JSON of translation and use the path as a string to access the translation.
const i18n = new Translit({
translation: {
en: {
hello: {
world: 'Hello world'
}
}
}
});
console.log(i18n.t('hello.world'));
// => Hello world
If you need a more complex translation, with pluralisation for example, you can simple define a method that takes a param and return a string.
const i18n = new Translit({
translation: {
en: {
itemInList: (count) => `This list contains ${count} item${count > 1 ? 's' : ''}.`
}
}
});
console.log(i18n.t('itemInList', 1));
// => This list contains 1 item
console.log(i18n.t('itemInList', 2));
// => This list contains 2 items
To use Translit inside a LitElement, just call the this.t
method inside your template
render() {
return html`
<section>
<p>${this.t('text.hi')}</p>
</section>
`;
}
- Translation : An object containing the translation.
- Locale : The current locale used for translation.
Locale : The language string.
Dynamically change the locale translation.
Translation : A translation object.
Dynamically add a new translation.
Translation : A string representing the path for the translation. Data : The data to be passed the translate function. Locale : The locale of the translation (override the default locale).
Translate a given string from the translation object.