loty
v0.1.1
Published
The tiny localization library for any framework
Downloads
275
Maintainers
Readme
🦜 Loty
Loty is a tiny, unopinionated localization library. It loads your translations from JSON files and lazily parses them with the formatter of your choice.
Highlights
- Tiny bundle size starting at 523 bytes (gzipped 364 bytes)
- Type safety with autocompletion in editor
- Customizable message formatter
- Messages are parsed lazily
- Loads missing messages from base locale
- Open source and fully tested with 100 % coverage
- Framework agnostic
Example
import { loty, LoaderReturn } from "loty";
import IntlMessageFormat from "intl-messageformat";
const lt = loty({
baseLocale: "en",
formatter(message, locale) {
return new IntlMessageFormat(message, locale);
},
});
// try to load german translations
// fallback to baseLocale
const t = await lt(
(locale) =>
import(
`./messages.${locale}.json`
) as LoaderReturn<typeof import("./messages.en.json")>,
"de"
);
// the translations are fully type safe
console.log(t.greeting.format({ name: "Jude" })); // Hey Jude
// nested objects work out of the box
console.log(t.hello.world.format()); // Hello World// messages.en.json
{
"greeting": "Hey {name}",
"hello": {
"world": "Hello World"
}
}Installation
- Run
pnpm install -D loty - In
tsconfig.jsonset compilerOptions.resolveJsonModule totrue
Usage with Unicode locale identifiers
If you want to localize dates and currencies to the region, but only got translations per language, you can extract the language from the locale identifier with Intl.Locale:
const t = await lt(
(locale) =>
import(
`./messages.${new Intl.Locale(locale).language}.json`
) as LoaderReturn<typeof import("./messages.en.json")>,
"en-US"
);