@absolutesight/gettext
v1.0.0
Published
High-performance, zero-dependency universal gettext i18n library for React, Next.js, Node.js, and all JavaScript frameworks with complete WordPress function parity, safe AST plural evaluator, PO/MO/JSON parsers, and JSX interpolation.
Maintainers
Readme
@absolutesight/gettext
The Universal, Zero-Dependency Gettext i18n Engine for React, Next.js, Node.js, and all JavaScript Frameworks — with 100% WordPress Parity and Native PO/MO/JSON Parsers.
⚡ Overview
@absolutesight/gettext is a high-performance, enterprise-grade internationalization (i18n) and localization (l10n) library written in strict TypeScript. It brings complete WordPress gettext API parity (__(), _x(), _n(), _nx(), _e(), sprintf(), etc.) to modern JavaScript and TypeScript environments with zero runtime dependencies.
Whether you are migrating a WordPress application to a headless Next.js frontend, building microservices in Node.js, or localizing a React/Vue/Svelte single-page application, @absolutesight/gettext provides everything needed out of the box:
- 🎯 100% WordPress Gettext Function Parity: Exact function names and signatures, plus modern camelCase aliases.
- 🔒 Zero Runtime Dependencies & Secure: No
eval()ornew Function(). Includes a custom recursive-descent AST plural expression evaluator compliant with strict Content Security Policies (CSP). - 🧩 First-Class React & JSX Support:
<Translate>,<Plural>,<GettextProvider>, anduseGettext()hook with safe component interpolation (nodangerouslySetInnerHTML). - ⚡ Multi-Format Parsers: Direct support for GNU Gettext
.pofiles, compiled binary.mofiles, and Jed / Gutenberg JSON formats. - 🌐 Isomorphic & Universal: Runs identically in Browser, Node.js, Next.js (App & Pages Router), Cloudflare Workers, Deno, and Bun.
- 🛡️ Thread-Safe & SSR-Ready: Supports both a global singleton (WordPress-style) and isolated instances (
createGettext()) to eliminate cross-request locale leakage in multi-tenant SSR applications.
📦 Installation
# npm
npm install @absolutesight/gettext
# pnpm
pnpm add @absolutesight/gettext
# yarn
yarn add @absolutesight/gettextNote: For React features (
@absolutesight/gettext/react),react >= 16.8.0is an optional peer dependency. Non-React or headless Node.js environments do not need React installed.
🚀 Quick Start
1. WordPress-Style Global Usage (Vanilla JS / Any Framework)
import {
__,
_x,
_n,
sprintf,
load_textdomain,
set_locale
} from '@absolutesight/gettext';
// 1. Load translations (from JSON, PO string, or catalog object)
load_textdomain('my-app', {
headers: { 'Plural-Forms': 'nplurals=2; plural=(n != 1);' },
entries: {
'Hello World': ['Hola Mundo'],
'btn\x04Submit': ['Enviar formulario'],
'%d item': ['%d artículo', '%d artículos']
}
}, 'es');
// 2. Switch locale
set_locale('es');
// 3. Translate with exact WordPress functions!
console.log(__('Hello World', 'my-app'));
// Output: Hola Mundo
console.log(_x('Submit', 'btn', 'my-app'));
// Output: Enviar formulario
console.log(sprintf(_n('%d item', '%d items', 5, 'my-app'), 5));
// Output: 5 artículos⚛️ React & Next.js Integration
Using <GettextProvider> and the useGettext() Hook
import React from 'react';
import { GettextProvider, useGettext, Translate, Plural } from '@absolutesight/gettext/react';
import { createGettext } from '@absolutesight/gettext';
// Create an instance or configure translations
const i18n = createGettext({ locale: 'es' });
i18n.loadTextdomain('default', {
entries: {
'Welcome %s': ['Bienvenido %s'],
'%d notification': ['%d notificación', '%d notificaciones'],
'Read our <link>terms</link>': ['Lea nuestros <link>términos</link>']
}
});
export function App() {
return (
<GettextProvider instance={i18n}>
<UserProfile username="Maria" unreadCount={3} />
</GettextProvider>
);
}
function UserProfile({ username, unreadCount }: { username: string; unreadCount: number }) {
const { __, sprintf } = useGettext();
return (
<main>
{/* 1. Component-based translation with placeholder */}
<Translate message="Welcome %s" values={[username]} as="h1" />
{/* 2. Plural translation component */}
<Plural
singular="%d notification"
plural="%d notifications"
count={unreadCount}
as="p"
/>
{/* 3. Safe JSX tag interpolation (replaces <link> with a React <a/>) */}
<Translate
message="Read our <link>terms</link>"
components={{
link: (children) => <a href="/terms">{children}</a>
}}
as="footer"
/>
</main>
);
}💡 Simple Text vs. JSX: Details and Considerations
When localizing web applications, working with simple plain text versus rich JSX elements presents distinct challenges. Here is how @absolutesight/gettext addresses them:
1. Simple Text Interpolation
For simple strings, standard sprintf specifiers (%s, %d, %f, %1$s) or named tokens ({name}) should be used:
sprintf(__('Hello %s, you have %d points'), 'Alice', 100);
// Or named syntax:
sprintf(__('Hello {user}, balance: {amount}'), { user: 'Alice', amount: '$50' });2. Embedded JSX Components & Interactive Elements
Often translations require embedded markup, such as links (<a>), bold text (<strong>), or interactive buttons.
⚠️ Issues with Common Approaches:
dangerouslySetInnerHTML: Passing translated HTML strings directly intodangerouslySetInnerHTMLexposes applications to Cross-Site Scripting (XSS) vulnerabilities if translation files are manipulated or contributed by untrusted translators.- String splitting: Splitting strings manually (e.g.
__('Click') + <a href="..."> + __('here')) breaks sentence structure across languages with different grammatical word orders. - React Key Warnings: Dynamically generated node arrays can trigger missing
keywarnings in React development.
✅ How @absolutesight/gettext Solves This:
The <Translate> component parses XML-style tags (like <link>...</link> or <bold>...</bold>) via an internal AST parser and converts them into React element trees without using dangerouslySetInnerHTML.
- Children are automatically preserved and passed to your renderer.
- Stable, unique React keys are assigned automatically.
- Translators can move tags anywhere in the sentence to match the natural grammar of the target language.
<Translate
message="Please <loginLink>sign in</loginLink> to view your <profileLink>account</profileLink>."
components={{
loginLink: (children) => <a href="/login" className="link">{children}</a>,
profileLink: (children) => <a href="/profile" className="link">{children}</a>
}}
/>📑 WordPress Function Parity & Aliases
@absolutesight/gettext provides identical function signatures to WordPress i18n, along with camelCase equivalents:
| WordPress Function | Modern CamelCase Alias | Description |
| :--- | :--- | :--- |
| __(text, domain?) | translate(text, domain?) | Translates a string for the active locale. |
| _e(text, domain?) | _e(text, domain?) | Translates a string and prints/echoes it (using configured logger). |
| _x(text, context, domain?) | translateWithContext(...) | Translates a string with disambiguating gettext context. |
| _ex(text, context, domain?)| _ex(text, context, domain?)| Translates with context and prints/echoes. |
| _n(single, plural, count, domain?) | translatePlural(...) | Translates singular or plural form based on count. |
| _nx(single, plural, count, ctxt, domain?) | translatePluralWithContext(...) | Translates singular/plural form with context. |
| _n_noop(single, plural, domain?) | _n_noop(...) | Registers plural strings without translating immediately. |
| _nx_noop(single, plural, ctxt, domain?) | _nx_noop(...) | Registers plural strings with context for later translation. |
| translate_noops(noop, count, domain?) | translateNoops(...) | Translates a noop-registered array. |
| load_textdomain(domain, data, locale?) | loadTextdomain(...) | Loads translation data into the domain catalog. |
| unload_textdomain(domain, locale?) | unloadTextdomain(...) | Unloads a domain catalog from memory. |
| is_textdomain_loaded(domain, locale?) | isTextdomainLoaded(...) | Returns true if the domain is loaded. |
| get_locale() | getLocale() | Returns the active locale string (e.g. 'en', 'es_ES'). |
| set_locale(locale) | setLocale(locale) | Updates the active locale. |
| reset_locale() | resetLocale() | Resets the active locale to the default configured locale. |
| sprintf(format, ...args) | sprintf(format, ...args) | Full printf/sprintf formatter supporting %s, %d, %1$s, etc. |
🗂️ File Formats & Node.js Loaders
The package includes subpath @absolutesight/gettext/node with filesystem loaders for .po, binary .mo, and .json files:
import {
loadPoFile,
loadPoFileSync,
loadMoFile,
loadMoFileSync,
loadJsonFile,
loadJsonFileSync
} from '@absolutesight/gettext/node';
import { __, set_locale } from '@absolutesight/gettext';
// Synchronous loading
loadPoFileSync('./locales/es.po', 'default', { locale: 'es' });
// Asynchronous binary .mo loading
await loadMoFile('./locales/fr.mo', 'default', { locale: 'fr' });
// JSON loading (Jed or Gutenberg format)
await loadJsonFile('./locales/de.json', 'default', { locale: 'de' });
set_locale('es');
console.log(__('Welcome'));Supported PO Syntax
- Comments (
#,#:,#.,#,,#|) - Multiline string continuation (
"string " \n "continuation") - Disambiguating context (
msgctxt "noun") - Singular and plural forms (
msgid,msgid_plural,msgstr[0],msgstr[1]) - Full header parsing (
Plural-Forms,Language,Content-Type)
Supported MO Syntax
- Compiled binary format (GNU Gettext
.mo) - Little Endian (
0x950412de) and Big Endian (0xde120495) - NUL-separated plural entries and
\x04contextual keys
🛠️ Complete Gettext Guide for Beginners (From Zero to Production)
If you are new to gettext, this section explains the entire workflow, what files are needed, required operating system tools, and how to automate extraction, translation, and compilation.
📚 Understanding the Gettext File Lifecycle
Gettext organizes translations into three primary file types:
┌────────────────────────────────────────────────────────┐
│ Source Code (*.js, *.ts, *.tsx) │
│ Contains: __('Hello World'), _n('%d item', ...) │
└──────────────────────────┬─────────────────────────────┘
│ 1. Extraction (xgettext)
▼
┌────────────────────────────────────────────────────────┐
│ .POT (Portable Object Template) - e.g. messages.pot │
│ Blank template containing all extracted source text │
└──────────────────────────┬─────────────────────────────┘
│ 2. Translation (Poedit / Weblate)
▼
┌────────────────────────────────────────────────────────┐
│ .PO (Portable Object) - e.g. es.po, fr.po, de.po │
│ Human-readable translation files per language │
└──────────────────────────┬─────────────────────────────┘
│ 3. Build / Compilation (Optional)
┌──────────────┴──────────────┐
▼ ▼
┌───────────────────────┐ ┌────────────────────────┐
│ .MO (Machine Object) │ │ .JSON (Web / Next.js) │
│ Binary compiled file │ │ Client-side bundle │
└───────────────────────┘ └────────────────────────┘.pot(Template): Generated automatically from your code. Contains all strings needing translation with emptymsgstr ""values. Translators never edit this file directly..po(Translations): Created from the.pottemplate for each language (e.g.,locales/es.pofor Spanish). Translators edit this file..mo/.json(Runtime formats): Optional compiled output for ultra-fast lookup and client-side consumption.
💻 Operating System Dependencies
To extract strings and compile .mo files from the command line, you need the official GNU gettext utilities (xgettext, msgfmt, msgmerge).
Install them on your operating system:
| Operating System | Installation Command |
| :--- | :--- |
| Ubuntu / Debian / WSL2 | sudo apt update && sudo apt install -y gettext |
| macOS (Homebrew) | brew install gettext && brew link --force gettext |
| Windows (PowerShell) | winget install GNU.Gettext (or choco install gettext) |
| Docker / Alpine Linux | apk add gettext gettext-dev |
| CentOS / RHEL / Fedora | sudo dnf install gettext |
Verify installation by running:
xgettext --version
msgfmt --version🔍 Step 1: Extracting Strings into a .pot Template
To scan your TypeScript and JavaScript files and create a .pot file, use GNU xgettext.
Notice the -k flags that instruct the parser to detect WordPress function names, contexts, and plurals:
# Create locales directory
mkdir -p locales
# Extract strings from all .ts, .tsx, .js, and .jsx files
xgettext \
--language=JavaScript \
--from-code=UTF-8 \
--output=locales/messages.pot \
--keyword=__ \
--keyword=_e \
--keyword=_x:1,2c \
--keyword=_ex:1,2c \
--keyword=_n:1,2 \
--keyword=_nx:1,2,4c \
--keyword=_n_noop:1,2 \
--keyword=_nx_noop:1,2,3c \
$(find src -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx")Tip: You can save this as an npm script in
package.json:"scripts": { "i18n:extract": "xgettext --language=JavaScript --from-code=UTF-8 --output=locales/messages.pot --keyword=__ --keyword=_e --keyword=_x:1,2c --keyword=_ex:1,2c --keyword=_n:1,2 --keyword=_nx:1,2,4c --keyword=_n_noop:1,2 --keyword=_nx_noop:1,2,3c $(find src -name '*.ts' -o -name '*.tsx')" }
✍️ Step 2: Translating .po Files
Initializing a new language
To create a new language translation file from your .pot template:
# Using msginit (interactive)
msginit --input=locales/messages.pot --output=locales/es.po --locale=es
# Or simply copy the template
cp locales/messages.pot locales/es.poUpdating existing .po files when code changes
When you add new strings to your codebase, re-run xgettext to update messages.pot, then merge changes into existing language files without losing past translations:
msgmerge --update locales/es.po locales/messages.pot
msgmerge --update locales/fr.po locales/messages.pot🖥️ Recommended Translation Software
Translators do not need to edit raw text files manually. They can use graphical tools:
- Poedit (Free, Windows / macOS / Linux): The industry gold standard for
.poand.potediting. Features built-in plural form validation, translation memory, and spellchecking. - Weblate (Open Source, Web-based): Excellent for teams and continuous localization directly synced with GitLab / GitHub merge requests.
- Crowdin & Transifex: Enterprise collaborative localization platforms with native PO/POT import/export.
- VS Code Extension: Gettext for in-editor PO syntax highlighting.
⚙️ Step 3: Compiling to .mo and Converting to .json
Do you need to convert .po files?
- No, conversion is optional!
@absolutesight/gettexthas a built-in zero-dependency PO parser. You can load.pofiles directly in Node.js or browsers vialoadPoFile()orparsePo(). - Why convert to
.mo? Binary.mofiles load significantly faster and use less RAM on high-throughput backend services. - Why convert to
.json? JSON is ideal for frontend React/Next.js client-side bundles because it is natively parsable by browser JavaScript engines and easy to fetch viafetch('/locales/es.json').
1. Compiling .po to binary .mo (msgfmt)
Use the GNU msgfmt command:
msgfmt -o locales/es.mo locales/es.poTo compile all .po files in your locales/ directory in one command:
for file in locales/*.po; do
msgfmt -o "${file%.po}.mo" "$file"
done2. Converting .po to .json (Zero-Dependency Node Script)
Because @absolutesight/gettext has a built-in parsePo parser, you can convert .po files into web-ready JSON in just a few lines of Node.js with zero external dependencies:
Create scripts/po2json.mjs:
import fs from 'node:fs';
import path from 'node:path';
import { parsePo } from '@absolutesight/gettext';
const localesDir = './locales';
const files = fs.readdirSync(localesDir).filter((f) => f.endsWith('.po'));
for (const file of files) {
const poPath = path.join(localesDir, file);
const jsonPath = path.join(localesDir, file.replace(/\.po$/, '.json'));
const poContent = fs.readFileSync(poPath, 'utf-8');
const catalog = parsePo(poContent);
fs.writeFileSync(jsonPath, JSON.stringify(catalog, null, 2), 'utf-8');
console.log(`✓ Converted ${file} -> ${path.basename(jsonPath)}`);
}Run it anytime with:
node scripts/po2json.mjs🚀 Step 4: Automating with CI/CD (GitLab CI & GitHub Actions)
When translators commit new or updated .po files, your CI/CD pipeline can automatically validate them and generate .mo and .json artifacts.
Example .gitlab-ci.yml:
stages:
- i18n
- build
compile-translations:
stage: i18n
image: node:20-alpine
before_script:
- apk add --no-cache gettext
- npm ci
script:
# 1. Compile all PO files to binary MO files
- for f in locales/*.po; do msgfmt -o "${f%.po}.mo" "$f"; done
# 2. Convert all PO files to web JSON
- node scripts/po2json.mjs
artifacts:
paths:
- locales/*.mo
- locales/*.json
expire_in: 1 week🛡️ Security and Zero Dependencies
Safe AST Plural Evaluator (No eval)
Many traditional gettext libraries compile plural equations via new Function('n', 'return ...') or eval(). This creates:
- CSP Violations: Crashes in environments with strict Content Security Policies (
unsafe-evaldisabled). - Arbitrary Code Execution (ACE): Vulnerabilities when loading translation files from external APIs, CMS platforms, or community contributors.
@absolutesight/gettext implements a pure mathematical Abstract Syntax Tree (AST) parser and evaluator for all gettext ternary and arithmetic formulas:
- Evaluates
(n%10==1 && n%100!=11 ? 0 : ...)securely. - 100% CSP compliant.
- Safe in Next.js Server Components, Edge Workers, and sandboxed runtimes.
🖥️ Server-Side Rendering (Next.js & Node.js)
To prevent cross-request locale leaks in concurrent environments (like Next.js App Router, Express, or Fastify), use isolated instances with createGettext():
import { createGettext } from '@absolutesight/gettext';
export function handleRequest(req, res) {
// Create an isolated instance for this specific request
const reqLocale = req.headers['accept-language']?.startsWith('fr') ? 'fr' : 'en';
const i18n = createGettext({ locale: reqLocale });
i18n.loadTextdomain('app', getCatalogFor(reqLocale));
const pageHtml = renderPage(i18n);
res.send(pageHtml);
}🧪 Testing & Quality Assurance
The codebase maintains strict zero-warning compliance and 100% unit test coverage:
# Run unit tests
npm test
# Type checking
npm run typecheck
# Lint check (strict 0 warnings)
npm run lint
# Production build
npm run build🤝 Contributing & Source Repository
The official repository is hosted on GitLab:
- Repository: https://gitlab.com/absolutesight/gettext
- Issue Tracker: https://gitlab.com/absolutesight/gettext/-/issues
Pull requests, feature suggestions, and bug reports are welcome!
📄 License
Released under the MIT License. Copyright © 2026 AbsoluteSight.
