Skip to content

XXanderWP/LangModule

Repository files navigation

translate-module logo

npm version npm downloads Publish npm Package License: MIT TypeScript

@xxanderwp/translate-module

A lightweight, type-safe TypeScript module for managing multi-language translations with support for interpolation placeholders.

Features

  • Full TypeScript generic type safety — language keys and translation keys are statically inferred
  • Runtime language switching via a simple setter
  • String interpolation with indexed placeholders ({0}, {1}, ...)
  • Language change listeners with automatic unregister support
  • Zero runtime dependencies

Installation

npm install @xxanderwp/translate-module

Usage

Basic setup

import { LanguageCore } from "@xxanderwp/translate-module";

const translations = {
  en: {
    greeting: "Hello, {0}!",
    farewell: "Goodbye!",
  },
  es: {
    greeting: "¡Hola, {0}!",
    farewell: "¡Adiós!",
  },
};

const lang = new LanguageCore(translations, "en");

lang.translate("greeting", "Alice"); // "Hello, Alice!"

Switching language

lang.currentLanguage = "es";
lang.translate("greeting", "Alice"); // "¡Hola, Alice!"

Accessing available languages

lang.langKeys; // ["en", "es"]

API

new LanguageCore(data, defaultLanguage?)

Parameter Type Description
data T An object mapping language keys to their translation dictionaries.
defaultLanguage keyof T (Optional) The language to activate on construction. Defaults to the first key in data.

Throws if data is empty or defaultLanguage is not a key of data.


translate(key, ...args)

Returns the translated string for key in the current language, with {0}, {1}, ... placeholders replaced by the provided args.

Returns the key itself as a string if the translation is missing.


currentLanguage (getter / setter)

Gets or sets the active language key. Setting an unsupported key throws an error.


langKeys

Returns an array of all available language keys.


languagesData

Returns the full translations object passed to the constructor.


currentLanguageData

Returns the translation dictionary for the currently active language.


onChangeLanguage(cb)

Registers a callback to be invoked whenever the active language changes. Returns an unregister function — call it to remove the listener.

const unregister = lang.onChangeLanguage(() => {
  console.log("Language changed to:", lang.currentLanguage);
});

// Later, to stop listening:
unregister();

Development

Build

npm run build

Run tests

npm test

Run tests with coverage

npm run test:coverage

License

MIT

About

A lightweight, type-safe TypeScript module for managing multi-language translations with support for interpolation placeholders

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors