Usage
Initialize
import Hermes from '@fca.gg/hermes';
Hermes.init();
init() takes no argument: it reads hermes.config.js when it exists, then the translations.json file from the build directory. Run hermes build first. Calling init() a second time throws an error.
The default language is the first one of fallbackChains.default (en-US unless you change it). If it is missing from the translations, init() throws an error.
Get a context
A translation is always read through a language context:
const ctx = Hermes.getContext('en-US');
ctx.t('hello'); // "Hello World!"
ctx.t('nested.key'); // "This is a nested key"
ctx.lang; // "en-US"
getContext('default')returns the context of the default language.- A language missing from the translations falls back to the default language.
t()is an alias oftranslate().
If a key does not exist in the context's language, t() throws an error. The build already fills missing keys from the fallback languages and warns you about gaps: keep checkTranslations on.
Pass variables
The second argument of t() provides the values of variables and expressions:
ctx.t('greeting', {name: 'Alice'});
The full syntax is described in formatting.
Scope
The second argument of getContext() sets a scope: a prefix added to every key, handy for a module or a command.
const ctx = Hermes.getContext('en-US', 'nested');
ctx.t('key'); // same as 'nested.key'
The scope is joined to the key with a dot.
Nested files
A language can be split across a directory, on several levels:
locales/
en-US.json
fr.json
en-GB/
common.json
auth.json
features/
feature1.json
feature2.json
The build merges these files into a single flat structure. Keys follow the file paths:
const ctx = Hermes.getContext('en-GB');
ctx.t('common.key');
ctx.t('features.feature1.key');
The separator depends on the keys option.
Localized objects
getLocalizedObject() returns the value of a key in every language that holds it. That is the format Discord expects for localized command names and descriptions.
const names = Hermes.getLocalizedObject('commands.ping.name');
// { "en-US": "ping", "fr": "ping", "de": "ping", ... }
The returned type is LocalizedObject, that is Partial<Record<Langs, string>>. If no language holds the key, the method throws an error.