Skip to content

A JavaScript implementation of gettext, a localization framework.

License

Notifications You must be signed in to change notification settings

postalsys/gettext

 
 

Repository files navigation

@postalsys/gettext

Note: This is a fork of alexanderwallin/node-gettext with additional enhancements and maintenance updates.

@postalsys/gettext is a JavaScript implementation of a substantial subset of GNU gettext, a powerful localization framework originally written in C. This library enables developers to internationalize their JavaScript applications by handling translations, plural forms, and contexts, closely mirroring the functionality of the original gettext.

If you're interested in parsing or compiling .mo/.po files for use with this library or elsewhere, consider using gettext-parser.

Table of Contents

Features

  • Comprehensive Localization Support: Handles domains, contexts, plurals, and more.
  • File Format Compatibility: Supports .json, .mo, and .po files via gettext-parser.
  • Extensive Language Support: Includes plural forms for 136 languages.
  • Dynamic Configuration: Allows changing locale or domain at runtime.
  • Debugging Tools: Provides detailed error messages when the debug option is enabled.
  • Event Emission: Emits events for internal errors, such as missing translations.

Differences from GNU gettext

While @postalsys/gettext aims to closely emulate GNU gettext, there are notable differences:

  1. No Category Support: Unlike GNU gettext, which supports categories like LC_MESSAGES, LC_NUMERIC, and LC_MONETARY, this library focuses solely on message localization, effectively always operating under the LC_MESSAGES category. For number formatting, currencies, dates, and other localization needs, consider using dedicated JavaScript libraries.
  2. Manual Translation Loading: GNU gettext automatically reads translation files from the filesystem based on locale and category settings. In contrast, @postalsys/gettext requires developers to manually load and provide translations, accommodating both server-side and client-side environments.

Installation

Install the package via npm:

npm install @postalsys/gettext

Usage

Basic Example

const Gettext = require('@postalsys/gettext');
const swedishTranslations = require('./translations/sv-SE.json');

const gt = new Gettext();
gt.addTranslations('sv-SE', 'messages', swedishTranslations);
gt.setLocale('sv-SE');

console.log(gt.gettext('The world is a funny place'));
// Output: "Världen är en underlig plats"

Error Events

@postalsys/gettext emits an error event when it encounters issues such as missing translations. You can handle these events as follows:

// Set up your Gettext instance and add translations...

gt.on('error', error => {
    console.error('Translation error:', error.message);
});

gt.gettext('An unrecognized message');
// Logs: 'Translation error: No translation found for msgid "An unrecognized message"'

Recipes

Loading Translations from .mo or .po Files

@postalsys/gettext works seamlessly with translations parsed by gettext-parser. Here's how you can load translations from .po files:

const fs = require('fs');
const path = require('path');
const Gettext = require('@postalsys/gettext');
const { po } = require('gettext-parser');

// Directory where your translations are stored
const translationsDir = 'path/to/locales';
const locales = ['en', 'fi-FI', 'sv-SE'];
const domain = 'messages';

const gt = new Gettext();

locales.forEach(locale => {
    const filename = `${domain}.po`;
    const translationsFilePath = path.join(translationsDir, locale, filename);
    const translationsContent = fs.readFileSync(translationsFilePath);

    const parsedTranslations = po.parse(translationsContent);
    gt.addTranslations(locale, domain, parsedTranslations);
});

gt.setLocale('sv-SE');
console.log(gt.gettext('Hello'));
// Outputs the translated string in Swedish

API Reference

Gettext

new Gettext([options])

Creates and returns a new Gettext instance.

Returns: Object - A Gettext instance
Params

  • [options]: Object - A set of options
    • .sourceLocale: String - The locale that the source code and its texts are written in. Translations for this locale is not necessary.
    • .debug: Boolean - Whether to output debug info into the console.

gettext.on(eventName, callback)

Adds an event listener.

Params

  • eventName: String - An event name
  • callback: function - An event handler function

gettext.off(eventName, callback)

Removes an event listener.

Params

  • eventName: String - An event name
  • callback: function - A previously registered event handler function

gettext.addTranslations(locale, domain, translations)

Stores a set of translations in the set of gettext catalogs.

Params

  • locale: String - A locale string
  • domain: String - A domain name
  • translations: Object - An object of gettext-parser JSON shape

Example

gt.addTranslations('sv-SE', 'messages', translationsObject)

gettext.setLocale(locale)

Sets the locale to get translated messages for.

Params

  • locale: String - A locale

Example

gt.setLocale('sv-SE')

gettext.setTextDomain(domain)

Sets the default gettext domain.

Params

  • domain: String - A gettext domain name

Example

gt.setTextDomain('domainname')

gettext.gettext(msgid) ⇒ String

Translates a string using the default textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • msgid: String - String to be translated

Example

gt.gettext('Some text')

gettext.dgettext(domain, msgid) ⇒ String

Translates a string using a specific domain

Returns: String - Translation or the original string if no translation was found
Params

  • domain: String - A gettext domain name
  • msgid: String - String to be translated

Example

gt.dgettext('domainname', 'Some text')

gettext.ngettext(msgid, msgidPlural, count) ⇒ String

Translates a plural string using the default textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • msgid: String - String to be translated when count is not plural
  • msgidPlural: String - String to be translated when count is plural
  • count: Number - Number count for the plural

Example

gt.ngettext('One thing', 'Many things', numberOfThings)

gettext.dngettext(domain, msgid, msgidPlural, count) ⇒ String

Translates a plural string using a specific textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • domain: String - A gettext domain name
  • msgid: String - String to be translated when count is not plural
  • msgidPlural: String - String to be translated when count is plural
  • count: Number - Number count for the plural

Example

gt.dngettext('domainname', 'One thing', 'Many things', numberOfThings)

gettext.pgettext(msgctxt, msgid) ⇒ String

Translates a string from a specific context using the default textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • msgctxt: String - Translation context
  • msgid: String - String to be translated

Example

gt.pgettext('sports', 'Back')

gettext.dpgettext(domain, msgctxt, msgid) ⇒ String

Translates a string from a specific context using s specific textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • domain: String - A gettext domain name
  • msgctxt: String - Translation context
  • msgid: String - String to be translated

Example

gt.dpgettext('domainname', 'sports', 'Back')

gettext.npgettext(msgctxt, msgid, msgidPlural, count) ⇒ String

Translates a plural string from a specific context using the default textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • msgctxt: String - Translation context
  • msgid: String - String to be translated when count is not plural
  • msgidPlural: String - String to be translated when count is plural
  • count: Number - Number count for the plural

Example

gt.npgettext('sports', 'Back', '%d backs', numberOfBacks)

gettext.dnpgettext(domain, msgctxt, msgid, msgidPlural, count) ⇒ String

Translates a plural string from a specifi context using a specific textdomain

Returns: String - Translation or the original string if no translation was found
Params

  • domain: String - A gettext domain name
  • msgctxt: String - Translation context
  • msgid: String - String to be translated
  • msgidPlural: String - If no translation was found, return this on count!=1
  • count: Number - Number count for the plural

Example

gt.dnpgettext('domainname', 'sports', 'Back', '%d backs', numberOfBacks)

License

This project is licensed under the MIT License. See the LICENSE file for details.

See Also

  • gettext-parser - Parse and compile gettext translations between .po/.mo files and JSON.
  • lioness - Gettext library for React applications.
  • react-gettext-parser - Extract translatable strings from React components.
  • narp - CLI tool for synchronizing translations between your app and Transifex.

About

A JavaScript implementation of gettext, a localization framework.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%