language-management-lib
v1.0.3
Published
A TypeScript library for managing language translations in applications with URL parameter support.
Maintainers
Readme
Language Management Library
A powerful TypeScript library for managing language translations in applications with automatic URL parameter detection and React support.
Features
- 🌍 Multi-language Support: Easy management of multiple language translations
- 🔗 URL Parameter Integration: Automatic language detection from URL parameters (
?lng=enor?language=en) - ⚛️ React Hook: Built-in
useTranslationhook for React applications - 🔄 Dynamic Translation Loading: Add new translations at runtime
- 🎯 TypeScript Support: Fully typed with excellent IntelliSense support
- 🏃♂️ Lightweight: Minimal dependencies, works in both browser and Node.js environments
- 🔧 Framework Agnostic: Core functionality works with any JavaScript framework
- 🛡️ Fallback System: Automatic fallback to default language when translations are missing
Installation
npm install language-management-libFor React projects, you'll also need React 16.8+ (for hooks support):
npm install react react-domQuick Start
Basic Usage
import { SetLanguage } from "language-management-lib";
const languages = {
en: {
welcome: "Welcome to our website!",
login: "Login",
about: "About Us",
},
es: {
welcome: "¡Bienvenido a nuestro sitio web!",
login: "Iniciar Sesión",
about: "Acerca de Nosotros",
},
fr: {
welcome: "Bienvenue sur notre site web!",
login: "Connexion",
about: "À Propos",
},
};
// Initialize with default language (automatically detects from URL)
const languageManager = new SetLanguage(languages, "en");
// Get translations
console.log(languageManager.translate("welcome"));
// Output: "Welcome to our website!" (or URL language if detected)
// Change language
languageManager.setLanguage("es");
console.log(languageManager.translate("welcome"));
// Output: "¡Bienvenido a nuestro sitio web!"React Usage
import React from "react";
import { SetLanguage, useTranslation } from "language-management-lib";
const languages = {
en: {
welcome: "Welcome!",
login: "Login",
about: "About Us",
},
es: {
welcome: "¡Bienvenido!",
login: "Iniciar Sesión",
about: "Acerca de Nosotros",
},
};
const languageManager = new SetLanguage(languages, "en");
function App() {
const { t, currentLanguage, changeLanguage, availableLanguages } =
useTranslation(languageManager);
return (
<div>
<h1>{t("welcome")}</h1>
<p>Current language: {currentLanguage}</p>
{/* Language selector */}
<div>
{availableLanguages.map((lang) => (
<button
key={lang}
onClick={() => changeLanguage(lang)}
style={{
backgroundColor: currentLanguage === lang ? "#007bff" : "#f8f9fa",
margin: "0 5px",
padding: "8px 12px",
}}
>
{lang.toUpperCase()}
</button>
))}
</div>
<button>{t("login")}</button>
<p>{t("about")}</p>
</div>
);
}
export default App;URL Parameter Integration
The library automatically detects language from URL parameters on initialization:
?lng=es- Sets language to Spanish?language=fr- Sets language to French- Both parameter formats are supported for maximum flexibility
// Language will be automatically detected from URL on initialization
const languageManager = new SetLanguage(languages, "en");
// URL: https://example.com?lng=es
console.log(languageManager.getCurrentLanguage()); // Output: "es"
// Programmatically change language and optionally update URL
languageManager.setLanguage("fr", true); // Updates URL to ?lng=fr
languageManager.setLanguage("en", false); // Changes language without updating URLAPI Reference
SetLanguage Class
Constructor
new SetLanguage<T>(languages: T, defaultLanguage?: string)Parameters:
languages: Object containing all language translationsdefaultLanguage: Default language code (defaults to "en")
Methods
translate(key: string): string
Get translation for a key. Falls back to default language if translation is missing.
languageManager.translate("welcome"); // Returns translated stringsetLanguage(language: string, updateURL?: boolean): void
Change current language and optionally update URL parameter.
languageManager.setLanguage("es"); // Changes language
languageManager.setLanguage("fr", true); // Changes language and updates URL
languageManager.setLanguage("de", false); // Changes language without updating URLgetCurrentLanguage(): string
Get the current active language code.
const currentLang = languageManager.getCurrentLanguage(); // Returns: "en", "es", etc.getAvailableLanguages(): string[]
Get array of all available language codes.
const languages = languageManager.getAvailableLanguages(); // Returns: ["en", "es", "fr"]addTranslations(language: string, translations: Record<string, string>): void
Add new translations for a language (creates language if it doesn't exist).
languageManager.addTranslations("de", {
welcome: "Willkommen!",
login: "Anmelden",
});getLanguageData(): T
Get the complete language data object.
const allData = languageManager.getLanguageData();useTranslation Hook (React)
const {
t, // Translation function: (key: string) => string
currentLanguage, // Current language code: string
changeLanguage, // Change language: (lang: string, updateURL?: boolean) => void
addTranslations, // Add translations: (lang: string, translations: Record<string, string>) => void
availableLanguages, // Available languages: string[]
} = useTranslation(languageManager);Advanced Examples
Adding Translations Dynamically
// Add new language at runtime
languageManager.addTranslations("de", {
welcome: "Willkommen!",
login: "Anmelden",
about: "Über uns",
});
// Add more translations to existing language
languageManager.addTranslations("de", {
contact: "Kontakt",
});
languageManager.setLanguage("de");
console.log(languageManager.translate("welcome")); // Output: "Willkommen!"Fallback Handling
// If a translation is missing, it automatically falls back to the default language
const languages = {
en: {
welcome: "Welcome!",
goodbye: "Goodbye!",
contact: "Contact Us",
},
es: {
welcome: "¡Bienvenido!",
// Missing 'goodbye' and 'contact'
},
};
const manager = new SetLanguage(languages, "en");
manager.setLanguage("es");
console.log(manager.translate("welcome")); // Output: "¡Bienvenido!"
console.log(manager.translate("goodbye")); // Output: "Goodbye!" (fallback to English)
console.log(manager.translate("contact")); // Output: "Contact Us" (fallback to English)
console.log(manager.translate("missing")); // Output: "missing" (returns key if not found)Using with Pre-defined Language Object
import { SetLanguage, lng } from "language-management-lib";
// Use the built-in sample language object
const languageManager = new SetLanguage(lng, "en");
console.log(languageManager.translate("welcome")); // Uses built-in translations
console.log(languageManager.getAvailableLanguages()); // ["en", "ka", "de"]React Hook with Dynamic Updates
import React, { useEffect } from "react";
import { SetLanguage, useTranslation } from "language-management-lib";
const languageManager = new SetLanguage(
{
en: { title: "My App", loading: "Loading..." },
es: { title: "Mi Aplicación", loading: "Cargando..." },
},
"en"
);
function MyComponent() {
const { t, changeLanguage, addTranslations, currentLanguage } =
useTranslation(languageManager);
useEffect(() => {
// Dynamically load more translations
addTranslations("fr", {
title: "Mon Application",
loading: "Chargement...",
});
}, [addTranslations]);
return (
<div>
<h1>{t("title")}</h1>
<p>{t("loading")}</p>
<select
value={currentLanguage}
onChange={(e) => changeLanguage(e.target.value, true)}
>
<option value="en">English</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</div>
);
}TypeScript Support
The library is fully typed and provides excellent IntelliSense support:
// Type-safe language definitions
const languages = {
en: {
welcome: "Welcome!",
login: "Login",
},
es: {
welcome: "¡Bienvenido!",
login: "Iniciar Sesión",
},
} as const;
// TypeScript will infer the correct types
const manager = new SetLanguage(languages, "en");
// IntelliSense will suggest available translation keys
manager.translate("welcome"); // ✅ TypeScript knows this key exists
manager.translate("invalid"); // ⚠️ TypeScript will warn about unknown keyBrowser Support
- Modern Browsers: Chrome 60+, Firefox 55+, Safari 12+, Edge 79+
- Node.js: 12.0.0+
- TypeScript: 4.0+
- React: 16.8+ (for hooks support)
Performance Notes
- Lightweight: ~3KB gzipped
- No external dependencies for core functionality
- Efficient translation lookup with O(1) complexity
- React hooks use proper memoization to prevent unnecessary re-renders
Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
MIT License - see LICENSE file for details.
Changelog
v1.0.0
- Initial release
- Core SetLanguage class with TypeScript support
- Automatic URL parameter detection (
?lng=and?language=) - React hook for easy integration
- Dynamic translation loading
- Fallback system for missing translations
- Comprehensive examples and documentation
