StrongLoop Globalize
strong-globalize is a JavaScript library for internationalization and localization (often called globalization) within Node.js applications. Currently at version 6.0.6, it provides a comprehensive API for formatting messages, currencies, dates, and numbers, as well as utility wrappers for Node.js console and `util.format`. It builds upon the Unicode CLDR data and the `jquery/globalize` library, offering features like autonomous message loading, runtime language switching, pseudo-localization, and deep string resource extraction from various file types (JSON, YAML, HTML). The library also includes command-line tools for extracting, linting, and translating strings from source code, facilitating a complete globalization workflow. It targets Node.js version 10 and above, ensuring compatibility with modern Node.js environments.
Common errors
-
Error: Message 'app.greeting' not found for locale 'en'.
cause The requested message key was not found in the loaded message catalog for the current locale, or the message file was not loaded correctly for that locale.fixVerify that the message key (`app.greeting`) exists in your locale-specific message files (e.g., `en.json`, `en.yaml`) and that `SG.SetRootDir` is pointing to the correct directory. Also, ensure messages are added via `SG.addMessages` if managed programmatically. -
TypeError: g.formatMessage is not a function
cause The 'g' object was not correctly imported or initialized, or the `require` statement did not resolve to the expected globalization instance containing the formatting methods.fixEnsure that you are importing 'g' correctly (e.g., `import g from 'strong-globalize';` or `const g = require('strong-globalize');` in CommonJS) and that the library is fully initialized before attempting to call its methods. -
Locale data for 'en' is missing. Please ensure the locale data for 'en' is loaded.
cause The underlying `jquery/globalize` library, which `strong-globalize` builds upon, cannot find the necessary CLDR locale data for the specified language ('en').fixInstall and explicitly load the required CLDR data for all locales your application supports. This often involves using `Globalize.load(cldrData)` from `jquery/globalize` after retrieving the appropriate CLDR JSON files. Check the `strong-globalize` documentation for guidance on automatic CLDR data loading if configured with `SG.SetRootDir`.
Warnings
- breaking As of strong-globalize v5.0.0, the package explicitly requires Node.js version 10 or higher. Running it on earlier Node.js versions (e.g., 8.x) will result in runtime errors and is not supported.
- gotcha strong-globalize relies on Unicode CLDR data for accurate internationalization. If locale data for a target language is missing or incorrectly loaded, formatting functions might produce incorrect output, fall back to default locales, or throw errors.
- gotcha There's a distinction between global language configuration via `SG.SetDefaultLanguage` and instance-specific language switching using `g.setLanguage`. `SG.SetDefaultLanguage` affects the global default, while `g.setLanguage` changes the locale for a particular 'g' instance. For multi-tenant or per-request localization in Node.js, manage 'g' instances carefully to avoid cross-request language contamination.
Install
-
npm install strong-globalize -
yarn add strong-globalize -
pnpm add strong-globalize
Imports
- g
const g = require('strong-globalize').g;import g, { SG } from 'strong-globalize'; - SG
import SG from 'strong-globalize';
import { SG } from 'strong-globalize'; - Types
import type { G, SG as SGType } from 'strong-globalize';
Quickstart
import g, { SG } from 'strong-globalize';
import path from 'path';
// Set the root directory for message files (e.g., 'locales/en.json') and default language
// In a real app, 'locales' might be in a dist folder or root.
SG.SetRootDir(path.join(process.cwd(), 'locales'));
SG.SetDefaultLanguage('en');
// Manually add messages for demonstration. In a real app, these would typically be loaded
// from JSON/YAML files located in the rootDir or added by the CLI 'extract' command.
SG.addMessages('en', {
'app.greeting': 'Hello, {name}!',
'app.welcome': 'Welcome to strong-globalize. Today is {date}.',
'app.price': 'The price is {0, currency} at {1, number} units.'
});
SG.addMessages('fr', {
'app.greeting': 'Bonjour, {name}!',
'app.welcome': 'Bienvenue à strong-globalize. Aujourd\'hui, nous sommes le {date}.',
'app.price': 'Le prix est de {0, currency} pour {1, number} unités.'
});
// Change language at runtime for the 'g' instance (e.g., based on user preference)
g.setLanguage('en');
console.log(g.f('app.greeting', { name: 'World' }));
console.log(g.formatMessage('app.welcome', { date: new Date() }));
console.log(g.c(123.45, 'USD')); // Defaults to US dollar format
console.log(g.formatCurrency(543.21, 'EUR', { minimumFractionDigits: 2, maximumFractionDigits: 2 }));
// Switch to French
g.setLanguage('fr');
console.log(g.f('app.greeting', { name: 'Monde' }));
console.log(g.formatMessage('app.welcome', { date: new Date() }));
console.log(g.d(new Date(), { skeleton: 'long' })); // Date formatting
console.log(g.n(1234567.89, { maximumFractionDigits: 0 })); // Number formatting
// Example using RFC 5424 Syslog severity wrappers
g.error('A critical error occurred: {reason}', { reason: 'disk full' });
g.warning('Potential issue: {count} warnings detected.', { count: 3 });