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.
- 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.
While @postalsys/gettext
aims to closely emulate GNU gettext, there are notable differences:
- No Category Support: Unlike GNU gettext, which supports categories like
LC_MESSAGES
,LC_NUMERIC
, andLC_MONETARY
, this library focuses solely on message localization, effectively always operating under theLC_MESSAGES
category. For number formatting, currencies, dates, and other localization needs, consider using dedicated JavaScript libraries. - 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.
Install the package via npm:
npm install @postalsys/gettext
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"
@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"'
@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
- Gettext
- new Gettext([options])
- .on(eventName, callback)
- .off(eventName, callback)
- .addTranslations(locale, domain, translations)
- .setLocale(locale)
- .setTextDomain(domain)
- .gettext(msgid) ⇒
String
- .dgettext(domain, msgid) ⇒
String
- .ngettext(msgid, msgidPlural, count) ⇒
String
- .dngettext(domain, msgid, msgidPlural, count) ⇒
String
- .pgettext(msgctxt, msgid) ⇒
String
- .dpgettext(domain, msgctxt, msgid) ⇒
String
- .npgettext(msgctxt, msgid, msgidPlural, count) ⇒
String
- .dnpgettext(domain, msgctxt, msgid, msgidPlural, count) ⇒
String
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.
Adds an event listener.
Params
eventName
:String
- An event namecallback
:function
- An event handler function
Removes an event listener.
Params
eventName
:String
- An event namecallback
:function
- A previously registered event handler function
Stores a set of translations in the set of gettext catalogs.
Params
locale
:String
- A locale stringdomain
:String
- A domain nametranslations
:Object
- An object of gettext-parser JSON shape
Example
gt.addTranslations('sv-SE', 'messages', translationsObject)
Sets the locale to get translated messages for.
Params
locale
:String
- A locale
Example
gt.setLocale('sv-SE')
Sets the default gettext domain.
Params
domain
:String
- A gettext domain name
Example
gt.setTextDomain('domainname')
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')
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 namemsgid
:String
- String to be translated
Example
gt.dgettext('domainname', 'Some text')
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 pluralmsgidPlural
:String
- String to be translated when count is pluralcount
:Number
- Number count for the plural
Example
gt.ngettext('One thing', 'Many things', numberOfThings)
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 namemsgid
:String
- String to be translated when count is not pluralmsgidPlural
:String
- String to be translated when count is pluralcount
:Number
- Number count for the plural
Example
gt.dngettext('domainname', 'One thing', 'Many things', numberOfThings)
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 contextmsgid
:String
- String to be translated
Example
gt.pgettext('sports', 'Back')
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 namemsgctxt
:String
- Translation contextmsgid
:String
- String to be translated
Example
gt.dpgettext('domainname', 'sports', 'Back')
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 contextmsgid
:String
- String to be translated when count is not pluralmsgidPlural
:String
- String to be translated when count is pluralcount
:Number
- Number count for the plural
Example
gt.npgettext('sports', 'Back', '%d backs', numberOfBacks)
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 namemsgctxt
:String
- Translation contextmsgid
:String
- String to be translatedmsgidPlural
:String
- If no translation was found, return this on count!=1count
:Number
- Number count for the plural
Example
gt.dnpgettext('domainname', 'sports', 'Back', '%d backs', numberOfBacks)
This project is licensed under the MIT License. See the LICENSE file for details.
- 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.