README
Simple and easy-to-use localization for JavaScript applications.
Set up
Create localize function as follows:
const localize = createLocalizerFactory({
en: {
greetGuest: 'Greetings, Guest',
greetUser: params => `Greetings, ${params.firstName}`,
greetClient: (params, localize) => params ? localize('greetUser', params) : localize('greetGuest'),
ka: {
greetGuest: 'გამარჯობა სტუმარო',
greetUser: params => `გამარჯობა ${params.firstName}`,
greetClient: (params, localize) => params ? localize('greetUser', params) : localize('greetGuest'),
},
})('en')
Above, createLocalizerFactory takes an object where keys are mapped to objects containing translations. Translation can either be static or dynamic.
- Static translations are plain strings.
- Dynamic translations take payload and
localize
function and return string.
createLocalizerFactory
returns memoized function which in turn takes default locale
and when called, returns localize function.
Usage
Considering the above set-up:
localize('greetGuest')
returns "Greetings, Guest" - because default locale is "en".localize('gretGuestt')
returns "gretGuestt" - because neither there is such key as "gretGuestt" under "en" translations above, nor a fallback is specified.localize('gretGuestt', null, 'Hey there')
returns "Hey there" - because, although there is no such key as "gretGuestt" under "en" translations above, but "Hey there" is specified as a fallback.localize('greetGuest', 'ka')
returns "გამარჯობა სტუმარო" - because, although default locale is "en", a custom "ka" locale is passed tolocalize
as a fourth argument.localize('greetGuest', null, '', 'ka')
returns "გამარჯობა სტუმარო" - because, although default locale is "en", a custom "ka" locale is passed tolocalize
as a fourth argument.localize('greetClient')
returns "Greetings, Guest" when the underline function evaluates.localize('greetClient', { firstName: 'user123' })
returns "Greetings, user123" when the underline function evaluates.