@scrappydiscord/language v0.0.3
Scrappy Language
About
An easy language module for handling multilingual systems originally written as a module for Scrappy.
Install
NPM
npm install @scrappydiscord/language
Yarn
yarn add @scrappydiscord/language
Usage
The following examples is in TypeScript.
Initialize It
import { Language } from '@scrappydiscord/language';
const language = new Language('path/to/translations');
You can also customize the options listed here under DefaultOptions
by passing an object as the second argument to the constructor like so:
new Language('path/to/translations', {
returnKeyNotNull: true
});
The following options are currently available:
defaultLanguage
(default:en
) - The default language code to use, checkLanguageCodes
to see all available codes.replacementKey
(default:$
) - The character to use for placeholders.returnKeyNotNull
(default:false
) - Instead of returning null when a translation key is not found, it will return the key requested.
Getting a Translation
let title: string = language.get('title', 'en');
let greeting: string = language.get('greeting.generic', 'en');
Adding New Translations
Sometimes there is a need to add new strings to a translation after it's initially created. This library makes it easy.
language.addToTranslation('en', {
newString: 'Hello, world!',
foo: {
bar: 'foobar'
}
});
Replacements/Placeholders
Translations can even contain placeholders to be replaced at runtime with data. You can do this by default by using $
before the name. This can be changed using the replacementKey
option.
const language = new Language({
en: {
replaceme: 'Hello $somestring!'
}
});
language.get('replaceme', { somestring: 'World' }); // Will output "Hello World!"
Cross Linking Translations
I know you're asking, "But wait, what if I need to use other translations within a translation?" There can be many reasons to do this. Standard formatting, common strings, etc. You DON'T want to do this:
l.get('something', { something: language.get('anotherthing', { name: 'John Doe'})}); // This is ugly.
This package makes it easy! All you have to do is wrap the requested translation in {{ }}
and it will pick it up. The best thing about this? You can nest references within references within references.
Example
Let's take a username with a discriminator (like a Discord username) with a custom markdown link with a URL to Google.
const language = new Language({
en: {
userformat: {
discrim: '$id',
name: '$user',
formatted: '{{userformat.name}}#{{userformat.discrim}}'
},
links: {
google: 'https://google.com'
},
advertisement: 'Welcome {{userformat.formatted}}! Please visit us on {{links.google}}.'
}
});
language.get('advertisement', { user: 'user', id: '0000' });
// This will output: "Welcome user#0000! Please visit us on https://google.com."