1.0.2 • Published 10 months ago

@qntm-code/translation-key-store v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

@qntm-code/translation-key-store

A simple key-value store for translation strings.

GitHub release Tests codecov Quality Gate Status Reliability Rating Vulnerabilities Bugs Security Rating Maintainability Rating

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');
1.0.2

10 months ago

1.0.1

10 months ago

1.0.0

10 months ago