Library setup, configuration management, and initialization lifecycle for i18next-client.
Initialize the i18next library with configuration options and callback.
/**
* Initialize i18next with options and callback
* @param options - Configuration options object
* @param callback - Function called when initialization completes
*/
function init(options, callback): void;
/**
* Check if i18next has been initialized
* @returns True if initialized, false otherwise
*/
function isInitialized(): boolean;Usage Examples:
// Basic initialization
i18n.init({
lng: 'en-US',
fallbackLng: 'en',
resGetPath: 'locales/__lng__/__ns__.json'
}, function(t) {
console.log('i18next initialized');
console.log(t('welcome')); // Translation function passed to callback
});
// With pre-loaded resources
i18n.init({
lng: 'en',
resStore: {
en: {
translation: {
welcome: 'Welcome',
greeting: 'Hello __name__'
}
}
}
}, function(t) {
console.log(t('welcome')); // "Welcome"
});
// Check initialization status
if (i18n.isInitialized()) {
console.log('Library is ready');
}Comprehensive configuration system for customizing library behavior.
interface InitOptions {
// Language settings
lng?: string; // Target language
fallbackLng?: string | string[]; // Fallback language(s)
preload?: string[]; // Languages to preload
lowerCaseLng?: boolean; // Lowercase language codes
load?: string; // Language loading mode: 'all', 'current', 'unspecific'
// Namespace configuration
ns?: string | {
namespaces: string[]; // Available namespaces
defaultNs: string; // Default namespace
};
fallbackNS?: string | string[]; // Fallback namespaces
fallbackToDefaultNS?: boolean; // Fall back to default namespace
// Resource loading
resGetPath?: string; // Resource loading path pattern
resPostPath?: string; // Resource posting path pattern
resStore?: object; // Pre-loaded resource store
getAsync?: boolean; // Async resource loading
postAsync?: boolean; // Async resource posting
dynamicLoad?: boolean; // Dynamic resource loading
// Storage options
useLocalStorage?: boolean; // Use localStorage for caching
localStorageExpirationTime?: number; // Cache expiration time
useCookie?: boolean; // Use cookies for language persistence
cookieName?: string; // Cookie name
cookieExpirationTime?: number; // Cookie expiration
cookieDomain?: string; // Cookie domain
// Detection settings
detectLngQS?: string; // Query string parameter for language
detectLngFromLocalStorage?: boolean; // Detect from localStorage
// Interpolation settings
interpolationPrefix?: string; // Variable prefix (default: '__')
interpolationSuffix?: string; // Variable suffix (default: '__')
escapeInterpolation?: boolean; // Escape interpolated variables
// Pluralization
pluralSuffix?: string; // Plural suffix (default: '_plural')
// Separators
nsseparator?: string; // Namespace separator (default: ':')
keyseparator?: string; // Key separator (default: '.')
// Fallback behavior
fallbackOnNull?: boolean; // Fall back when value is null
fallbackOnEmpty?: boolean; // Fall back when value is empty
showKeyIfEmpty?: boolean; // Show key when value is empty
// Return format
returnObjectTrees?: boolean; // Return nested objects
// Integration
setJqueryExt?: boolean; // Enable jQuery extensions
// Missing key handling
sendMissing?: boolean; // Send missing keys to server
sendMissingTo?: string; // Where to send: 'fallback', 'current', 'all'
sendType?: string; // HTTP method for sending
missingKeyHandler?: function; // Custom missing key handler
parseMissingKey?: function; // Custom missing key parser
// Post-processing
postProcess?: string | string[]; // Post-processing steps
shortcutFunction?: string; // Shortcut function mode
// Debug and logging
debug?: boolean; // Enable debug logging
// Custom functions
functions?: object; // Override internal functions
objectTreeKeyHandler?: function; // Custom object tree handler
// Advanced options
defaultVariables?: object; // Default interpolation variables
maxRecursion?: number; // Max recursion for reuse
ajaxTimeout?: number; // AJAX request timeout
}Load additional languages before they are needed.
/**
* Preload additional languages
* @param lngs - Language codes to preload (string or array)
* @param callback - Function called when preloading completes
*/
function preload(lngs, callback): void;Usage Examples:
// Preload single language
i18n.preload('es', function() {
console.log('Spanish preloaded');
i18n.setLng('es'); // Switch to Spanish
});
// Preload multiple languages
i18n.preload(['es', 'fr', 'de'], function() {
console.log('Multiple languages preloaded');
});
// Preload during init
i18n.init({
lng: 'en',
preload: ['es', 'fr'], // Preload these languages
resGetPath: 'locales/__lng__/__ns__.json'
}, function(t) {
console.log('Init complete with preloaded languages');
});Reload all resources and reinitialize the library.
/**
* Reload resources and reinitialize
* @param callback - Function called when reload completes
*/
function reload(callback): void;Usage Examples:
// Reload all resources
i18n.reload(function() {
console.log('Resources reloaded');
});
// Reload and switch language
i18n.reload(function() {
i18n.setLng('es', function() {
console.log('Reloaded and switched to Spanish');
});
});i18n.init({
lng: 'en-US',
fallbackLng: 'en',
ns: {
namespaces: ['translation', 'common'],
defaultNs: 'translation'
},
resGetPath: 'locales/__lng__/__ns__.json',
useLocalStorage: true,
localStorageExpirationTime: 24 * 60 * 60 * 1000, // 24 hours
interpolationPrefix: '__',
interpolationSuffix: '__',
debug: true
}, function(t) {
// Start your application
console.log(t('app.title'));
});i18n.init({
lng: 'en',
fallbackLng: 'en',
preload: ['es', 'fr', 'de'], // Preload common languages
ns: {
namespaces: ['translation', 'navigation', 'forms'],
defaultNs: 'translation'
},
resGetPath: 'assets/i18n/__lng__/__ns__.json',
useLocalStorage: true,
detectLngFromLocalStorage: true,
fallbackOnNull: true,
fallbackOnEmpty: false,
returnObjectTrees: false,
interpolationPrefix: '{{',
interpolationSuffix: '}}',
setJqueryExt: true
}, function(t) {
// Initialize UI components
$('[data-i18n]').i18n(); // jQuery DOM localization
});i18n.init({
lng: 'en',
fallbackLng: 'en',
resStore: preloadedTranslations, // From server
ns: 'translation',
interpolationPrefix: '__',
interpolationSuffix: '__',
useCookie: false,
useLocalStorage: false,
getAsync: false // Synchronous for SSR
}, function(t) {
// Render application
});i18n.init({
lng: 'en',
resGetPath: 'locales/__lng__/__ns__.json',
sendMissing: true,
missingKeyHandler: function(lng, ns, key, defaultValue) {
console.warn(`Missing translation: ${lng}.${ns}.${key}`);
// Optionally send to analytics or logging service
}
}, function(err, t) {
if (err) {
console.error('i18next initialization failed:', err);
return;
}
console.log('i18next initialized successfully');
});