Rosetta
A general purpose internationalization library in 292 bytes
README
rosetta
Features
Simple and Familiar API
Unobstrusive and Unopinionated
Less than 300 bytes – including dependencies!
Install
- ``` null
- $ npm install --save rosetta
- ```
Usage
- ``` js
- import rosetta from 'rosetta';
- const i18n = rosetta({
- en: {
- intro: {
- welcome: 'Welcome, {{username}}!',
- text: 'I hope you find this useful.',
- },
- support(obj) {
- let hour = Math.floor(Math.random() * 3) + 9;
- let str = `For questions, I'm available on ${obj.date.toLocaleDateString()}`;
- str += `, any time after ${hour}:00.`
- return str;
- }
- }
- });
- // set default language
- i18n.locale('en');
- // add new language
- i18n.set('pt', {
- intro: {
- welcome: obj => `Benvind${obj.feminine ? 'a' : 'o'}, ${obj.username}!`,
- text: 'Espero que você ache isso útil.'
- }
- });
- // append extra key(s) to existing language
- i18n.set('pt', {
- support(obj) {
- let hour = Math.floor(Math.random() * 3) + 9;
- let str = `Se tiver perguntas, estou disponível em ${obj.date.toLocaleDateString()}`;
- str += `, qualquer hora depois às ${hour}:00.`
- return str;
- }
- });
- const data = {
- feminine: false,
- username: 'lukeed',
- date: new Date()
- };
- // Retrieve translations
- // NOTE: Relies on "en" default
- i18n.t('intro.welcome', data); //=> 'Welcome, lukeed!'
- i18n.t('intro.text', data); //=> 'I hope you find this useful.'
- i18n.t('support', data); //=> 'For questions, I'm available on 4/8/2020, any time after 11:00.'
- // Retrieve translations w/ lang override
- i18n.t('intro.welcome', data, 'pt'); //=> 'Benvindo, lukeed!'
- // Change default language key
- i18n.locale('pt');
- // Retrieve translations w/ new defaults
- i18n.t('intro.text', data); //=> 'Espero que você ache isso útil.'
- i18n.t('intro.text', data, 'en'); //=> 'I hope you find this useful.'
- ```
API
rosetta(dict?)
Returns: Rosetta
Initializes a new Rosettainstance.You may optionally provide an initial translation object.
rosetta.locale(lang?)
Returns: String
Sets the language code for the Rosettainstance.This will cause all rossetta.t() lookups to assume this langcode.
The function will return the currently active langcode. This means that a setting a new value will reply with the same value. Additionally, calling locale()without any argument will return the langcode that the Rosettainstance was last given.
lang
Type: StringRequired: false
The language code to choose.If locale()is called without an argument (or with a falsey value), then the current langcode is returned.
rosetta.set(lang, table)
Merge (or override) translation keys into the langcollection.
lang
Type: String
The language code to target.
table
Type: Object
A new record of key-values to merge into the lang's dictionary.
Each key within the tablecan correspond to a function or a string template.
When using a function, it will receive the entire data input (see params ).You are required to ensure the function returns a (string) value of your liking.
When using a string template, anything within double curly brackets ({{ example }}) will be interpreted as a key path and interpolated via templite . The key path can use dot-notation to access nested values from the data input (see params ). Additionally, if a key path did not resolve to a value, an empty string is injected.
- ``` js
- const ctx = rosetta({
- en: {
- foo: (obj) => `function sees "${obj.value || '~DEFAULT~'}"`,
- bar: 'template sees "{{value}}"'
- }
- });
- ctx.t('foo', {}, 'en');
- //=> 'function sees "~DEFAULT~"
- ctx.t('foo', { value: 123 }, 'en');
- //=> 'function sees "123"
- ctx.t('bar', {}, 'en');
- //=> 'template sees ""
- ctx.t('bar', { value: 123 }, 'en');
- //=> 'template sees "123"
- ```
Runtime Support
The library makes use of Object shorthand methods and Object.assign .This yields the following support matrix:
| Chrome | Safari | Firefox | Edge | IE | Node.js |
| :--- | :--- | :--- | :--- | :--- | :--- |
| 45+| 9+| 34+| 12+| ❌| 4.0+ |
If you need to support older platforms, simply attach rosettato your project's Babel (or similar) configuration.
Examples
Using Next.js — Thank you @StarpTech Official Next.js example using React Hooks and Context to provide SSR, SSG, CSR compatible i18n solutions.
Localization solution for Next.js — Lightweight Internationalization (i18n) library for Next.js 10+
Credits
Thank you @7sempra for gifting the rosettaname on npm.
License
MIT © Luke Edwards