@qntm-code/translation-key-store
v1.0.2
Published
Simple key-value store for translation keys and their values
Downloads
3
Readme
@qntm-code/translation-key-store
A simple key-value store for translation strings.
Installation
npm i @qntm-code/translation-key-store
or
yarn add @qntm-code/translation-key-store
Usage
First create a new store singleton. This can be done in a separate file and imported into other files.
import { TranslationKeyStore } from '@qntm-code/translation-key-store';
// Create a new store singleton
export const store = new TranslationKeyStore();
When creating your store you can optionally enable logging of missing translations:
import { TranslationKeyStore } from '@qntm-code/translation-key-store';
// Create a new store singleton
export const store = new TranslationKeyStore({ enableLogging: true });
Or you can provide your own missing translation handler:
import { TranslationKeyStore } from '@qntm-code/translation-key-store';
// Create a new store singleton
export const store = new TranslationKeyStore({
missingTranslationHandler: (language: string, key: string) => {
// Do something with the missing translation information
},
});
Once you have created your store you can populate it with translations:
// Populate the store with translations
store.addLanguageNamespace('en', 'my-namespace', {
'my-key': 'My translation',
'my-other-key': 'My other translation',
'my-parent-key': {
'my-child-key': 'My child translation',
},
});
// Populate the store with translations
store.addLanguageNamespace('fr', 'my-namespace', {
'my-key': 'Ma traduction',
'my-parent-key': {
'my-child-key': 'Traduction enfant',
},
});
You can then retrieve translations from the store. The function will return messageformat message functions for found values. If not it will return undefined.
const translation = store.getTranslationValue('my-namespace.my-key', 'en');
if (translation) {
const value = translation(); // My translation
}
You can provide a fallback language to the getTranslationValue
function. If the translation is not found in the requested language it will look in the fallback language.
const translation = store.getTranslationValue('my-namespace.my-other-key', 'fr', 'en');
if (translation) {
const value = translation(); // My other translation
}
You can remove stored languages if your user changes their language in a SPA and you want to free up memory:
store.removeLanguage('fr');