Skip to content

@plinthjs/localization ​

Plinth i18n. A small, deterministic, in-memory translator: per-locale message bags, dot-path lookups with a fallback locale, :name placeholder interpolation (with casing variants), and pluralization.

Usage ​

ts
import { Translator } from '@plinthjs/localization'

const t = new Translator({ locale: 'en', fallback: 'en' })

t.addMessages('en', {
  auth: { failed: 'These credentials do not match our records.' },
  welcome: 'Welcome, :Name!',
})
// flat dot-keyed lines also work:
t.addLines('en', { 'mail.greeting': 'Hello :name' })

t.get('auth.failed') // "These credentials do not match our records."
t.get('welcome', { name: 'taylor' }) // "Welcome, Taylor!"  (:Name capitalizes)
t.has('auth.failed') // true
t.get('does.not.exist') // "does.not.exist"  (missing -> the key itself)

Fallback locale ​

ts
const t = new Translator({ locale: 'fr', fallback: 'en' })
t.addMessages('en', { greeting: 'Hello' })
t.get('greeting') // "Hello"  (fr missing -> fallback en)

Pluralization ​

ts
const t = new Translator({ locale: 'en', fallback: 'en' })
t.addLines('en', {
  apples: 'There is one apple|There are many apples',
  notifications: '{0} No notifications|[1,19] :count notifications|[20,*] Lots of notifications',
})

t.choice('apples', 1) // "There is one apple"
t.choice('apples', 5) // "There are many apples"

t.choice('notifications', 0) // "No notifications"
t.choice('notifications', 5) // "5 notifications"  (:count injected automatically)
t.choice('notifications', 50) // "Lots of notifications"

API ​

  • new Translator({ locale, fallback })
  • addMessages(locale, nestedBag) / addLines(locale, flatRecord)
  • get(key, replacements?, locale?)
  • choice(key, count, replacements?, locale?)
  • has(key, locale?)
  • getLocale() / setLocale(locale) / setFallback(fallback)

Released under the MIT License.