The bare-bones internationalization library used by yargs
npx @tessl/cli install tessl/npm-y18n@5.0.0y18n is the bare-bones internationalization library used by yargs. It provides essential localization features including string translation with parameter substitution, pluralization support, template literal support, and automatic JSON-based locale file management.
npm install y18nconst y18n = require('y18n');ESM:
import y18n from 'y18n';Deno:
import y18n from "https://deno.land/x/y18n/deno.ts";const __ = require('y18n')().__;
const __n = require('y18n')().__n;
// Simple string translation
console.log(__('Hello %s', 'world'));
// Output: "Hello world"
// Template literal support
const name = 'Alice';
console.log(__`Hello ${name}!`);
// Output: "Hello Alice!"
// Pluralization
console.log(__n('one item', '%d items', 2));
// Output: "2 items"y18n is built around several key components:
y18n() function creates configured instances__ for simple translation, __n for pluralizationCreates a configured y18n instance with specified options.
/**
* Creates a y18n instance with the provided configuration
* @param opts - Configuration options
* @returns Object with translation methods and locale management
*/
function y18n(opts?: Y18NOpts): {
__: (str: string, ...args: string[]) => string;
__n: (singular: string, plural: string, count: number, ...args: string[]) => string;
setLocale: (locale: string) => void;
getLocale: () => string;
updateLocale: (obj: Locale) => void;
locale: string;
};
interface Y18NOpts {
/** The locale directory, defaults to './locales' */
directory?: string;
/** Should newly observed strings be updated in file, defaults to true */
updateFiles?: boolean;
/** What locale should be used, defaults to 'en' */
locale?: string;
/** Should fallback to language-only file be allowed, defaults to true */
fallbackToLanguage?: boolean;
}Translates strings with sprintf-style parameter substitution using %s placeholders.
/**
* Print a localized string, %s will be replaced with args
* Can also be used as a tag for template literals
* @param str - String to translate or template literal parts
* @param args - Values to substitute for %s placeholders, optionally ending with callback function
* @returns Translated string with substitutions
*/
__(str: string, ...args: (string | Function)[]): string;
__(parts: TemplateStringsArray, ...args: string[]): string;Usage Examples:
const __ = y18n({ locale: 'en' }).__;
// Basic translation with parameters
console.log(__('Welcome %s!', 'Alice'));
// Output: "Welcome Alice!"
// Multiple parameters
console.log(__('User %s has %s points', 'Bob', '150'));
// Output: "User Bob has 150 points"
// Template literal usage
const user = 'Charlie';
const score = 200;
console.log(__`User ${user} has ${score} points`);
// Output: "User Charlie has 200 points"
// With callback (called after locale file updates)
__('New message', 'param', function(err) {
if (err) console.error('Error updating locale file:', err);
else console.log('Locale file updated successfully');
});Provides pluralized translation with count-based selection between singular and plural forms.
/**
* Print a localized string with appropriate pluralization
* If %d is provided in the string, count will replace this placeholder
* @param singular - Singular form string
* @param plural - Plural form string
* @param count - Number to determine singular/plural and optional %d substitution
* @param args - Additional arguments for substitution, optionally ending with callback function
* @returns Appropriate singular/plural string with substitutions
*/
__n(singular: string, plural: string, count: number, ...args: (string | Function)[]): string;Usage Examples:
const __n = y18n({ locale: 'en' }).__n;
// Basic pluralization
console.log(__n('one item', '%d items', 1));
// Output: "one item"
console.log(__n('one item', '%d items', 5));
// Output: "5 items"
// With additional parameters
console.log(__n('one fish %s', '%d fishes %s', 2, 'swimming'));
// Output: "2 fishes swimming"
// With callback (called after locale file updates)
__n('one new item', '%d new items', 3, function(err) {
if (err) console.error('Error updating locale file:', err);
else console.log('Pluralization added to locale file');
});Methods for managing the current locale and updating translations.
/**
* Set the current locale being used
* @param locale - Locale string (e.g., 'en', 'fr', 'en_US')
*/
setLocale(locale: string): void;
/**
* Get the current locale being used
* @returns Current locale string
*/
getLocale(): string;
/**
* Update the current locale with key-value pairs
* @param obj - Object with translation key-value pairs
*/
updateLocale(obj: Locale): void;Usage Examples:
const i18n = y18n({ locale: 'en' });
// Change locale
i18n.setLocale('fr');
console.log(i18n.getLocale()); // Output: "fr"
// Update translations
i18n.updateLocale({
'Hello': 'Bonjour',
'Goodbye': 'Au revoir'
});
console.log(i18n.__('Hello')); // Output: "Bonjour"interface Locale {
[key: string]: string;
}
interface Y18NOpts {
directory?: string;
updateFiles?: boolean;
locale?: string;
fallbackToLanguage?: boolean;
}y18n automatically manages JSON locale files in the specified directory (defaults to ./locales). When new strings are encountered, they are automatically added to the appropriate locale file if updateFiles is enabled.
Locale File Structure:
{
"Hello %s": "Hello %s",
"one item": {
"one": "one item",
"other": "%d items"
}
}Fallback Behavior:
If a specific locale file (e.g., en_US.json) doesn't exist and fallbackToLanguage is true, y18n will attempt to use the language-only file (e.g., en.json).