gettext-to-messageformat
raw JSON → 0.4.0 verified Fri May 01 auth: no javascript
Converts gettext .po, .pot, and .mo files into messageformat-compatible JSON. Version 0.4.0, released as a stable library with no further updates expected. It uses gettext-parser under the hood and provides functions parsePo and parseMo that return headers, a plural function, and translations object. The plural function can be derived from the Plural-Forms header or provided manually. Key differentiator: bridges the gap between gettext tooling and messageformat-based internationalization in JavaScript, with support for plural forms and context.
Common errors
error Cannot find module 'gettext-to-messageformat' ↓
cause Package not installed or incorrect import path.
fix
Run
npm install gettext-to-messageformat and ensure the import path is correct. error TypeError: parsePo is not a function ↓
cause Incorrect import (default vs named).
fix
Use
const { parsePo } = require('gettext-to-messageformat') or import { parsePo } from 'gettext-to-messageformat'. error Invalid or unexpected token ↓
cause Input string is not valid gettext format.
fix
Ensure the input is a valid .po or .mo file content as a string or Buffer.
Warnings
breaking In v0.4.0, the option `sortByMsgId` was renamed to `sort`. ↓
fix Use `sort` option instead of `sortByMsgId`.
breaking In v0.4.0, output headers now use canonical case instead of forced lower-case. ↓
fix Access header keys with canonical case (e.g., 'Language' instead of 'language').
deprecated Node.js 6.0 is the minimum engine; older versions may break with deps. ↓
fix Upgrade Node.js to >=6.0.
gotcha If no headers are found, pluralFunction may be null; you must handle that. ↓
fix Check if pluralFunction is null and provide a fallback if needed.
Install
npm install gettext-to-messageformat yarn add gettext-to-messageformat pnpm add gettext-to-messageformat Imports
- parsePo wrong
const parsePo = require('gettext-to-messageformat').parsePocorrectconst { parsePo } = require('gettext-to-messageformat') - parseMo wrong
import parseMo from 'gettext-to-messageformat'correctimport { parseMo } from 'gettext-to-messageformat' - parsePo, parseMo wrong
const { parsePo, parseMo } = require('gettext-to-messageformat')correctimport { parsePo, parseMo } from 'gettext-to-messageformat'
Quickstart
const { parsePo } = require('gettext-to-messageformat');
const { headers, pluralFunction, translations } = parsePo(`
msgid ""
msgstr ""
"Language: pl\n"
"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n"
msgid "Time: %1 second"
msgid_plural "Time: %1 seconds"
msgstr[0] "Czas: %1 sekunda"
msgstr[1] "Czas: %1 sekundy"
msgstr[2] "Czas: %1 sekund"
`);
const MessageFormat = require('messageformat');
const mf = new MessageFormat({ [headers.Language]: pluralFunction });
const messages = mf.compile(translations);
console.log(messages['Time: %1 second']([1]));
// 'Czas: 1 sekunda'