Lightweight, type-safe internationalization library with property-based testing
npm install kiro-i18n{{variable}} syntax
bash
npm install @kiro/i18n
`
๐ Quick Start
`typescript
import { getI18nAPI } from '@kiro/i18n';
// Initialize the i18n system
const i18n = getI18nAPI({
localesPath: './locales',
defaultLanguage: 'en-US',
fallbackLanguage: 'en-US'
});
await i18n.initialize();
// Translate a key
const greeting = i18n.t('common.hello'); // "Hello"
// Translate with interpolation
const welcome = i18n.t('common.welcome', { name: 'Alice' }); // "Welcome Alice"
// Change language
await i18n.changeLanguage('zh-CN');
const greetingCN = i18n.t('common.hello'); // "ไฝ ๅฅฝ"
// Listen to language changes
i18n.onLanguageChange((newLanguage) => {
console.log(Language changed to: ${newLanguage});
});
`
๐ Project Structure
`
your-project/
โโโ locales/
โ โโโ languages.json # Language metadata
โ โโโ en-US/ # English translations
โ โ โโโ common.json
โ โ โโโ menu.json
โ โ โโโ settings.json
โ โโโ zh-CN/ # Simplified Chinese translations
โ โโโ common.json
โ โโโ menu.json
โ โโโ settings.json
โโโ src/
โโโ index.ts
`
๐ Translation File Format
Translation files use nested JSON structure:
`json
{
"menu": {
"file": {
"label": "ๆไปถ",
"open": "ๆๅผ",
"save": "ไฟๅญ"
}
},
"common": {
"welcome": "ๆฌข่ฟ {{name}}"
}
}
`
Access translations using dot-separated keys: menu.file.open
๐ง API Reference
$3
Get the singleton instance of the i18n API.
Config Options:
- localesPath: Path to translation files (default: 'locales')
- defaultLanguage: Default language code (default: 'en-US')
- fallbackLanguage: Fallback language code (default: 'en-US')
$3
#### initialize(): Promise
Initialize the i18n system and load the default language.
#### t(key: string, params?: Record
Translate a key with optional parameter interpolation.
#### changeLanguage(languageCode: LanguageCode): Promise
Change the current language.
#### getCurrentLanguage(): LanguageCode
Get the current language code.
#### getSupportedLanguages(): LanguageInfo[]
Get list of all supported languages.
#### onLanguageChange(callback: (language: LanguageCode) => void): () => void
Register a callback for language changes. Returns an unsubscribe function.
๐งช Testing
The library includes comprehensive test coverage with both unit tests and property-based tests:
`bash
Run all tests
npm test
Run tests in watch mode
npm run test:watch
Run tests with UI
npm run test:ui
Generate coverage report
npm run test:coverage
`
๐๏ธ Building
`bash
Build for production
npm run build
Build and watch for changes
npm run dev
Type check
npm run lint
`
๐ Language Metadata
Define supported languages in locales/languages.json:
`json
{
"languages": [
{
"code": "en-US",
"name": "English",
"nativeName": "English"
},
{
"code": "zh-CN",
"name": "Simplified Chinese",
"nativeName": "็ฎไฝไธญๆ"
}
]
}
``