0
# y18n
1
2
y18n 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.
3
4
## Package Information
5
6
- **Package Name**: y18n
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install y18n`
10
11
## Core Imports
12
13
```javascript
14
const y18n = require('y18n');
15
```
16
17
ESM:
18
19
```typescript
20
import y18n from 'y18n';
21
```
22
23
Deno:
24
25
```typescript
26
import y18n from "https://deno.land/x/y18n/deno.ts";
27
```
28
29
## Basic Usage
30
31
```javascript
32
const __ = require('y18n')().__;
33
const __n = require('y18n')().__n;
34
35
// Simple string translation
36
console.log(__('Hello %s', 'world'));
37
// Output: "Hello world"
38
39
// Template literal support
40
const name = 'Alice';
41
console.log(__`Hello ${name}!`);
42
// Output: "Hello Alice!"
43
44
// Pluralization
45
console.log(__n('one item', '%d items', 2));
46
// Output: "2 items"
47
```
48
49
## Architecture
50
51
y18n is built around several key components:
52
53
- **Factory Function**: The main `y18n()` function creates configured instances
54
- **Translation Methods**: `__` for simple translation, `__n` for pluralization
55
- **Locale Management**: Automatic JSON file reading/writing with fallback support
56
- **Platform Abstraction**: Separate shims for Node.js and Deno environments
57
- **Cache System**: In-memory caching of loaded locale data
58
59
## Capabilities
60
61
### Factory Function
62
63
Creates a configured y18n instance with specified options.
64
65
```typescript { .api }
66
/**
67
* Creates a y18n instance with the provided configuration
68
* @param opts - Configuration options
69
* @returns Object with translation methods and locale management
70
*/
71
function y18n(opts?: Y18NOpts): {
72
__: (str: string, ...args: string[]) => string;
73
__n: (singular: string, plural: string, count: number, ...args: string[]) => string;
74
setLocale: (locale: string) => void;
75
getLocale: () => string;
76
updateLocale: (obj: Locale) => void;
77
locale: string;
78
};
79
80
interface Y18NOpts {
81
/** The locale directory, defaults to './locales' */
82
directory?: string;
83
/** Should newly observed strings be updated in file, defaults to true */
84
updateFiles?: boolean;
85
/** What locale should be used, defaults to 'en' */
86
locale?: string;
87
/** Should fallback to language-only file be allowed, defaults to true */
88
fallbackToLanguage?: boolean;
89
}
90
```
91
92
### String Translation
93
94
Translates strings with sprintf-style parameter substitution using %s placeholders.
95
96
```typescript { .api }
97
/**
98
* Print a localized string, %s will be replaced with args
99
* Can also be used as a tag for template literals
100
* @param str - String to translate or template literal parts
101
* @param args - Values to substitute for %s placeholders, optionally ending with callback function
102
* @returns Translated string with substitutions
103
*/
104
__(str: string, ...args: (string | Function)[]): string;
105
__(parts: TemplateStringsArray, ...args: string[]): string;
106
```
107
108
**Usage Examples:**
109
110
```javascript
111
const __ = y18n({ locale: 'en' }).__;
112
113
// Basic translation with parameters
114
console.log(__('Welcome %s!', 'Alice'));
115
// Output: "Welcome Alice!"
116
117
// Multiple parameters
118
console.log(__('User %s has %s points', 'Bob', '150'));
119
// Output: "User Bob has 150 points"
120
121
// Template literal usage
122
const user = 'Charlie';
123
const score = 200;
124
console.log(__`User ${user} has ${score} points`);
125
// Output: "User Charlie has 200 points"
126
127
// With callback (called after locale file updates)
128
__('New message', 'param', function(err) {
129
if (err) console.error('Error updating locale file:', err);
130
else console.log('Locale file updated successfully');
131
});
132
```
133
134
### Pluralization
135
136
Provides pluralized translation with count-based selection between singular and plural forms.
137
138
```typescript { .api }
139
/**
140
* Print a localized string with appropriate pluralization
141
* If %d is provided in the string, count will replace this placeholder
142
* @param singular - Singular form string
143
* @param plural - Plural form string
144
* @param count - Number to determine singular/plural and optional %d substitution
145
* @param args - Additional arguments for substitution, optionally ending with callback function
146
* @returns Appropriate singular/plural string with substitutions
147
*/
148
__n(singular: string, plural: string, count: number, ...args: (string | Function)[]): string;
149
```
150
151
**Usage Examples:**
152
153
```javascript
154
const __n = y18n({ locale: 'en' }).__n;
155
156
// Basic pluralization
157
console.log(__n('one item', '%d items', 1));
158
// Output: "one item"
159
console.log(__n('one item', '%d items', 5));
160
// Output: "5 items"
161
162
// With additional parameters
163
console.log(__n('one fish %s', '%d fishes %s', 2, 'swimming'));
164
// Output: "2 fishes swimming"
165
166
// With callback (called after locale file updates)
167
__n('one new item', '%d new items', 3, function(err) {
168
if (err) console.error('Error updating locale file:', err);
169
else console.log('Pluralization added to locale file');
170
});
171
```
172
173
### Locale Management
174
175
Methods for managing the current locale and updating translations.
176
177
```typescript { .api }
178
/**
179
* Set the current locale being used
180
* @param locale - Locale string (e.g., 'en', 'fr', 'en_US')
181
*/
182
setLocale(locale: string): void;
183
184
/**
185
* Get the current locale being used
186
* @returns Current locale string
187
*/
188
getLocale(): string;
189
190
/**
191
* Update the current locale with key-value pairs
192
* @param obj - Object with translation key-value pairs
193
*/
194
updateLocale(obj: Locale): void;
195
```
196
197
**Usage Examples:**
198
199
```javascript
200
const i18n = y18n({ locale: 'en' });
201
202
// Change locale
203
i18n.setLocale('fr');
204
console.log(i18n.getLocale()); // Output: "fr"
205
206
// Update translations
207
i18n.updateLocale({
208
'Hello': 'Bonjour',
209
'Goodbye': 'Au revoir'
210
});
211
212
console.log(i18n.__('Hello')); // Output: "Bonjour"
213
```
214
215
## Types
216
217
```typescript { .api }
218
interface Locale {
219
[key: string]: string;
220
}
221
222
interface Y18NOpts {
223
directory?: string;
224
updateFiles?: boolean;
225
locale?: string;
226
fallbackToLanguage?: boolean;
227
}
228
```
229
230
## File System Integration
231
232
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.
233
234
**Locale File Structure:**
235
236
```json
237
{
238
"Hello %s": "Hello %s",
239
"one item": {
240
"one": "one item",
241
"other": "%d items"
242
}
243
}
244
```
245
246
**Fallback Behavior:**
247
248
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`).
249
250
## Error Handling
251
252
- **SyntaxError**: Thrown for malformed JSON locale files with descriptive error message including file path
253
- **File System Errors**: Missing locale files are handled gracefully by creating empty locale cache
254
- **Type Errors**: Invalid parameter types are handled by the underlying platform format functions