lokales
TypeScript icon, indicating that this package has built-in type declarations

1.2.4 • Public • Published

Lokales

Barebones i18n localization written in TypeScript. Similar to y18n but with a few improvements, handles errors better preventing corrupt or empty locale files. Other than that about the same.

New Version 1.1.x

Fixed graceful exit, ensures write before exit. Fix issue where directory isn't created, refactored simplified methods. Add method "sync" to synchronize all locales from a primary locale. This ensures your primary locale (probably "en") and it's keys exist in all other locales known on your system.

Quick Start

Initialize using ES5 or ES6/TypeScript Imports.

import { Lokales } from 'lokales';
const lokales = new Lokales({ /* your options */ });

OR ES5

const Lokales = require('lokales').Lokales;
const lokales = new Lokales({ /* your options */ });

Singular

Singular example passing key and format values.

lokales.__('Hello my name is %s.', 'Joe');
// Result > Hello my name is Joe.

Plural

Plural example passing singular key, plural key, count and format values.

lokales.__n('I have %d cat', 'I have %d cats', 2, 'Joe');
// Result > I have 2 cats.

Literal

Template literal example.

const color = 'blue';
lokales.__`My favorite color is ${color}.`;
// Result > My favorite color is blue.

Options

Options can also be set using the lokales.setOption(key, value) method.

KeyDescription
directoryThe directory where locales are stored.
localeThe active locale to be used.
updateWhen true localization file is updated when key is unknown.
onUpdateCustom callback called on locale file updated.
onErrorCustom callback called on error.

API

Simple API for plural or singular localization along with get and set for options.

MethodArgumentsDescription
__val: string, ...args: any[]Singular localization.
__nsingular: string, plural: string, count: number, ...args: any[]Plural localization.
setOptionkey: LokalesOptionKeys | ILokalesOptions, val: anySets an option by key/value or options object.
getOptionkey: stringGets an existing option.
keyExistskey: string, locale?: string, directory?: stringChecks if key exists in locale.

Advanced Usage

In some cases it may be useful to call a translate API after your primary localization file is updated. For example upon updating the en.json locale you may with to update perhaps the es, fr, ru or it locales. Here's an example using Google Translate.

IMPORTANT

A quick note about the below example. One key piece missing below for the sake of brevity is some sort of method to serialialize and deserialize the string to be translated. This is because the translate API won't typically know what to do with %s or %d. You can simply iterate the string and replace these tokens with tokens your translate API will ignore. The restructure the data after translation.

import { Lokales } from 'lokales';
import { translate } from '@google-cloud';
import { writeFile } from 'fs';
import { join } from 'path';
 
const lokales = new Lokales({ onUpdate: onUpdate });
const trans = translate({
  key: 'YOUR_API_KEY'
});
 
/**
 * On Update called when process queue updated locale.
 *
 * Updated Object Contains:
 * singular: string;  // The singular key string.
 * plural: string;    // The plural key if provided or null.
 * count: number;     // The count when plural is used.
 * args: [];          // The original format arguments passed.
 * options: {}        // Snapshot of options. (see options above for details)
 */
function onUpdate(err, updated, instance) {
 
  if (err)
    throw err; // do something with error.
 
  const value = updated.singular // you might check for plural here but for simplicity.
  const options = updated.options;
  const lang = 'es'; // the lang we want to translate to.
  const translated: any = {}; // object to store translated values.
 
  trans.translate(value, lang, (err, res) => {
 
    if (err)
      throw err;
 
    if (!Array.isArray(res)) // ensure our result is an array.
      res = [res];
 
    res.forEach((s, i) => {
      translated[s] = s; // see above important note.
    });
 
    const savePath = path.join(options.directory, lang + '.json');
    const serialized = JSON.stringify(translated, null, 2);
 
    fs.writeFile(savePath, serialized, (err) => {
      // do something with/if error.
      // or
      // log success etc.
    });
 
  });
 
}

Docs

See https://origin1tech.github.io/lokales/

License

See LICENSE.md

Dependencies (1)

Dev Dependencies (14)

Package Sidebar

Install

npm i lokales

Weekly Downloads

27

Version

1.2.4

License

ISC

Unpacked Size

691 kB

Total Files

46

Last publish

Collaborators

  • blujedis
  • origin1tech