CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-i18next

Internationalization framework for JavaScript applications with flexible backend support and plugin ecosystem

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

language-management.mddocs/

Language Management

Language detection, changing, loading, and managing language hierarchies with fallback support and text direction handling.

Capabilities

Change Language

Switch the current language and reload resources as needed.

/**
 * Change the current language
 * @param lng - Target language code
 * @param callback - Optional callback when language change completes
 * @returns Promise resolving to translation function
 */
function changeLanguage(lng?: string, callback?: Callback): Promise<TFunction>;

Usage Examples:

import i18next from "i18next";

// Change to specific language
await i18next.changeLanguage("de");
console.log(i18next.t("welcome")); // German translation

// Change with callback
i18next.changeLanguage("fr", (err, t) => {
  if (err) return console.error(err);
  console.log(t("welcome")); // French translation
});

// Auto-detect language (if language detector is configured)
await i18next.changeLanguage();

// Using the returned translation function
const t = await i18next.changeLanguage("es");
console.log(t("welcome")); // Spanish translation

Load Languages

Load additional languages not defined in initialization preload.

/**
 * Load additional languages
 * @param lngs - Language codes to load
 * @param callback - Optional callback when loading completes
 * @returns Promise resolving when loading completes
 */
function loadLanguages(lngs: string | readonly string[], callback?: Callback): Promise<void>;

Usage Examples:

// Load single language
await i18next.loadLanguages("it");

// Load multiple languages
await i18next.loadLanguages(["pt", "ru", "ja"]);

// With callback
i18next.loadLanguages(["ko", "zh"], (err) => {
  if (err) return console.error("Failed to load languages:", err);
  console.log("Languages loaded successfully");
});

// Load and switch to language
await i18next.loadLanguages("da");
await i18next.changeLanguage("da");

Text Direction

Get text direction (left-to-right or right-to-left) for languages.

/**
 * Get text direction for a language
 * @param lng - Language code (defaults to current language)
 * @returns Text direction
 */
function dir(lng?: string): 'ltr' | 'rtl';

Usage Examples:

// Get direction for current language
const direction = i18next.dir(); // 'ltr' or 'rtl'

// Get direction for specific language
const arabicDir = i18next.dir("ar"); // 'rtl'
const englishDir = i18next.dir("en"); // 'ltr'

// Use in CSS or styling
document.documentElement.setAttribute("dir", i18next.dir());

// Conditional styling
const textAlign = i18next.dir() === "rtl" ? "right" : "left";

Language Properties

Access current language state and hierarchy.

interface i18n {
  /** Current active language */
  language: string;
  /** Language hierarchy used for fallbacks */
  languages: readonly string[];
  /** Currently resolved language with available translations */
  resolvedLanguage?: string;
}

Usage Examples:

// Check current language
console.log(`Current language: ${i18next.language}`);

// View language hierarchy
console.log(`Language fallback chain: ${i18next.languages.join(" -> ")}`);

// Check resolved language
if (i18next.resolvedLanguage) {
  console.log(`Using translations from: ${i18next.resolvedLanguage}`);
}

// Language hierarchy example:
// If user language is "en-US" and fallbackLng is ["en", "dev"]
// languages might be: ["en-US", "en", "dev"]

Language Detection Integration

When using language detector modules, language management becomes automatic.

// Example with language detector
import i18next from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";

await i18next
  .use(LanguageDetector)
  .init({
    fallbackLng: "en",
    detection: {
      order: ["localStorage", "navigator", "htmlTag"],
      caches: ["localStorage"]
    }
  });

// Language is automatically detected and set
console.log(`Detected language: ${i18next.language}`);

Fallback Language Configuration

Configure sophisticated fallback strategies for robust language support.

type FallbackLng = 
  | string 
  | readonly string[] 
  | FallbackLngObjList 
  | ((code: string) => string | readonly string[] | FallbackLngObjList);

interface FallbackLngObjList {
  [language: string]: readonly string[];
}

Usage Examples:

// Simple string fallback
await i18next.init({
  fallbackLng: "en"
});

// Array of fallbacks
await i18next.init({
  fallbackLng: ["en", "de", "fr"]
});

// Object with specific fallbacks per language
await i18next.init({
  fallbackLng: {
    "en-US": ["en", "dev"],
    "en-GB": ["en", "dev"],
    "de-DE": ["de", "en", "dev"],
    "default": ["en", "dev"]
  }
});

// Function-based fallback logic
await i18next.init({
  fallbackLng: (code) => {
    if (code.startsWith("en")) return ["en", "dev"];
    if (code.startsWith("de")) return ["de", "en", "dev"];
    return ["en", "dev"];
  }
});

Language Loading Strategies

Control how languages are loaded and cached.

// Configuration options affecting language loading
await i18next.init({
  // Load strategy
  load: "all", // 'all' | 'currentOnly' | 'languageOnly'
  
  // Preload specific languages
  preload: ["en", "de", "fr"],
  
  // Supported languages (others will be filtered out)
  supportedLngs: ["en", "de", "fr", "es"],
  
  // Allow non-explicitly supported languages
  nonExplicitSupportedLngs: true,
  
  // Partial bundled languages (some resources bundled, others remote)
  partialBundledLanguages: true
});

Language Events

Monitor language changes and loading events.

// Language change events
i18next.on("languageChanging", (lng: string) => {
  console.log(`Changing to language: ${lng}`);
  // Show loading indicator
});

i18next.on("languageChanged", (lng: string) => {
  console.log(`Language changed to: ${lng}`);
  // Update UI direction
  document.documentElement.setAttribute("dir", i18next.dir(lng));
  // Hide loading indicator
});

// Resource loading events
i18next.on("loaded", (loaded) => {
  console.log("Resources loaded for languages:", Object.keys(loaded));
});

i18next.on("failedLoading", (lng, ns, msg) => {
  console.error(`Failed to load ${lng}:${ns} - ${msg}`);
  // Handle loading errors
});

Advanced Language Utilities

Internal language utilities available through services.

// Access language utilities (for advanced use cases)
const { languageUtils } = i18next.services;

// Get language part from code
const lang = languageUtils.getLanguagePartFromCode("en-US"); // "en"

// Get script part from code
const script = languageUtils.getScriptPartFromCode("zh-Hans-CN"); // "Hans"

// Get region part from code
const region = languageUtils.getRegionPartFromCode("en-US"); // "US"

// Format language code
const formatted = languageUtils.formatLanguageCode("EN_us"); // "en-US"

// Check if language is supported
const supported = languageUtils.isSupportedCode("de"); // boolean

// Get best match from available codes
const best = languageUtils.getBestMatchFromCodes(["en-GB", "en", "de"]);

// Get fallback codes for a language
const fallbacks = languageUtils.getFallbackCodes("en-US");
// Returns: ["en-US", "en", "dev"] (based on configuration)

// Resolve language hierarchy
const hierarchy = languageUtils.toResolveHierarchy("en-US");
// Returns: ["en-US", "en", "dev"] (based on configuration)

Supported Language Formats

i18next supports various language code formats:

// ISO 639-1 (two-letter)
"en", "de", "fr", "es", "ja", "zh"

// ISO 639-1 with region (BCP 47)
"en-US", "en-GB", "de-DE", "fr-CA", "pt-BR"

// With script tags
"zh-Hans", "zh-Hant", "sr-Latn", "sr-Cyrl"

// Complete BCP 47 tags
"zh-Hans-CN", "zh-Hant-TW", "en-US-POSIX"

// Special codes
"dev" // Development mode (returns keys as values)
"cimode" // Continuous integration mode (returns keys)

docs

index.md

instance-management.md

language-management.md

plugin-system.md

resource-management.md

translation.md

tile.json