I18n Module (node-yalc/i18n)
The I18n (Internationalization) module provides a lightweight engine for translating user-facing strings within the Ferrox-Node framework. It is particularly useful for returning localized error messages, emails, or push notifications based on the user's preferences.
Overview
Instead of hardcoding english strings, developers register language dictionaries with the I18nEngine. At runtime, the engine fetches the correct string based on the requested locale and injects dynamic variables.
Key Features
- Fallback Mechanism: If a translation is missing for the requested locale, it automatically falls back to the default locale (e.g.,
en). If it's still missing, it returns the raw key. - Variable Interpolation: Supports double-brace syntax
{{ variableName }}for dynamic text.
Usage Example
import { I18nEngine } from '@node-yalc/i18n';
// Initialize with 'en' as the fallback language
const i18n = new I18nEngine('en');
// Register English dictionary
i18n.registerTranslations('en', {
'ERR_USER_NOT_FOUND': 'The user {{ email }} could not be found.',
'WELCOME_MSG': 'Welcome to Ferrox, {{ name }}!'
});
// Register Italian dictionary
i18n.registerTranslations('it', {
'ERR_USER_NOT_FOUND': 'L\'utente {{ email }} non è stato trovato.',
// Notice WELCOME_MSG is intentionally missing here to demonstrate fallback
});
// 1. Basic Translation (Italian)
const errIt = i18n.translate('ERR_USER_NOT_FOUND', { email: 'test@example.com' }, 'it');
console.log(errIt); // "L'utente test@example.com non è stato trovato."
// 2. Fallback to Default Locale
const welcomeIt = i18n.translate('WELCOME_MSG', { name: 'Mario' }, 'it');
console.log(welcomeIt); // "Welcome to Ferrox, Mario!" (fell back to 'en')
// 3. Fallback to Raw Key
const unknown = i18n.translate('UNKNOWN_KEY', {}, 'fr');
console.log(unknown); // "UNKNOWN_KEY"
Best Practices
Instantiate I18nEngine as a singleton in your Dependency Injection container. Load your dictionaries from JSON files into the engine during application bootstrap.