A simple, lightweight localization system
npm install @sx3/i18n
Flexible localization system like a Fluent but for TypeScript.
- Small ~630 bytes gzip
- Support message functions (for pluralization or for any functions)
- Native pluralization
- Dependency free
- Type safe (for keys and message functions)
- Simple lazy loading
``bash`
bun add @sx3/i18n
`ts
import { createI18n } from '@sx3/i18n';
import { pluralize } from '@sx3/i18n/plural';
// Better to define in the localization file.
const EN_RULES = new Intl.PluralRules('en-US');
const { t } = createI18n({
locale: 'en',
locales: {
en: {
// Static string message
me: 'SX3',
// Functional messages
hello: (who: string) => Hello ${who}!,${who} liked the ${what}
user: {
liked: (who: string, what: string) => ${count} apples
},
// Pluralization with Intl.PluralRules
apple: pluralize({ one: 'apple', other: count => }, EN_RULES)
},
// Lazy loading locale
ru: () => import('./lang/ru').then(m => m.default)
},
// Fallbacks loads in background
fallbackLocales: { en: ['ru'] },
// Handle missing keys
onMissingKey: (key, locale) => {
console.warn(Key "${key}" not found in "${locale}" locale and their fallbacks);
// You can rewrite message for missing keys
return 'Unknown key';
}
});
t('hello', 'world'); // -> Hello world
t('non-existent'); // -> TypeScript error for non existent key
t('apple'); // -> TypeScript error need count argument specified
t('apple', 1); // -> apple
t('apple', 3); // -> 3 apples
t('user.liked', 'SX3', 'post'); // -> SX3 liked the post
`
`ts
import { createI18n } from '@sx3/i18n';
import { createApp, shallowReactive } from 'vue';
// Now store is reactive
const store = shallowReactive(new Map());
const i18n = createI18n({
locale: 'en',
store,
// ...other options
});
// Wait when main locale loaded
await i18n.isReady();
const app = createApp(App).mount('#app');
``