Simple and lightweight message localisation for JavaScript projects.
pnpm add @eartharoid/i18n
oryarn add @eartharoid/i18n
ornpm i @eartharoid/i18n
const I18n = require('@eartharoid/i18n');
const i18n = new I18n('english', {
english: {
example: 'Hello, world'
},
russian: {
example: 'https://www.youtube.com/watch?v=bwnksI2ZoJI'
}
});
// note: you should check if the locale exists in i18n.locales first
const __ = i18n.getLocale('russian'); // get the locale
console.log(__('example')); // -> https://www.youtube.com/watch?v=bwnksI2ZoJI
// this code does exactly the same
console.log(i18n.getMessage('russian', 'example'));
i18n supports both positional and named placeholders.
{ // a locale object
"positional": {
"strings": "I like %s",
"numbers": "%d %s %d = %d"
},
"named": {
"example1": "Hi, I'm {name} and I am from {location}",
"example2": "Hi, I'm {person.name} and I am from {person.location}"
}
}
Also note that messages and named placeholders can be nested
__('positional.strings', 'chocolate'); // I like chocolate
__('positional.numbers', 5, '+', 5, 10); // 5 + 5 = 10
__('named.example1', {
name: 'Someone',
location: 'Somewhere'
}); // Hi, I'm Someone and I am from Somewhere
__('named.example2', {
person: {
name: 'Someone',
location: 'Somewhere'
}
}); // Hi, I'm Someone and I am from Somewhere
i18n supports basic pluralisation. If the message is an array, the first placeholder value will be eaten and the correct message will be returned.
[
"1",
"anything else"
]
or
[
"0",
"1",
"anything else"
]
{ // a locale object
"example1": [
"You only have one %s",
"You have %d %ss"
],
"example2": [
"You don't have any {item}s",
"You only have one {item}",
"You have {number} {item}s"
]
}
__('example1', 1, 1, 'item')
__('example2', 0, {
number: 0,
item: 'car'
})
Create a new I18n instance
default_locale
- the name of the default localelocales
- an object of localised messages
The name of the default locale
An array of the names of the locales you created
Get a locale
locale
- locale name
Returns a function which calls I18n#getMessage
using the given locale name (or the default).
Get a message from a specifc
locale
- locale namemessage
- dot notation string for the message...args
- placeholders/pluralisation
© 2021 Isaac Saunders