chisarok
v0.1.0
Published
A fast, minimal-dependency i18n library.
Downloads
2
Readme
chisarok
Chisarok is a TypeScript library for handling locales in a simple manner.
Installation
If using yarn,
$ yarn add https://github.com/zeyla/chisarok.ts --save
If using npm,
$ npm install https://github.com/zeyla/chisarok.ts --save
Examples
Retrieve the translation string for the "user.greeting"
key for the default
locale, and binding values for replacement:
import Chisarok from "chisarok";
const chisarok = new Chisarok({
// When no locale is specified or the translation key does not exist for a
// requested locale, "en" is used. If `defaultFallback` is undefined, then no
// default fallback is used.
defaultFallback: "en",
// Load files from this directory.
directory: `${__dirname}/locales`,
// Specify which locales to load. If the directory contains translations for
// 4 languages - say "de", "en", "es", and "no", then you may specify to only
// load "de", "en", and "no".
locales: ["de", "en", "no"],
// The mapped fallbacks specify an order for locales to fallback to. In this
// instance, if a translation key for the "no" locale is requested but was not
// found, the "de" locale will be searched next. If one is still not found,
// then the "en" locale will be searched.
mappedFallbacks: {
"de": "en",
"no": "de",
},
});
(async () => {
// Load the locale files from the directory. In this example, the `locales`
// directory contains JSON files of objects with translation keys and strings.
//
// We pass the `JSON.parse` function to convert the format into a manner that
// makes sense to Chisarok.
//
// If the directory contained YAML files, you could pass a function that
// parses YAML instead.
await chisarok.load(JSON.parse);
// Assuming the `locales/en.json` file contained the content:
// {
// "user.greeting": "Hello {{name}}{{punctuation}}"
// }
const translated = chisarok._("user.greeting", {
// Performs an in-place replacement of the "name" key with "Jane".
name: "Jane",
// Replaces the "punctuation" key with "!"
punctuation: "!",
});
console.log(translated); // "Hello Jane!"
})();
Retrieve multiple keys' strings, useful for array destructuring:
import Chisarok from "chisarok";
const chisarok = new Chisarok({
defaultFallback: "en",
directory: `${__dirname}/locales`,
});
(async () => {
await chisarok.load(JSON.parse);
const [foo, bar] = chisarok._m("foo.world", "foo.bar");
console.log(foo); // "hello world!"
console.log(bar); // "foo bar baz"
})();
There are two ways of setting up your locale files. The first is a flat object representing keys and translation strings:
{
"foo.bar": "hello",
"foo.baz": "world",
"qux.quz": "."
}
The second is nesting objects to more easily represent the keys when editing a locale:
{
"foo": {
"bar": "hello",
"baz": "world"
},
"qux": {
"quz": "."
}
}
You may mix these two methods.
Refer to the API documentation for many examples on how to use each method.
License
This project is licensed under ISC.