Internationalization framework for JavaScript applications with flexible backend support and plugin ecosystem
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
i18next instance initialization, configuration, and lifecycle management including creating new instances and cloning existing ones.
Initialize i18next with configuration options and optional callback.
/**
* Initialize i18next instance
* @param options - Configuration options
* @param callback - Optional callback when initialization completes
* @returns Promise resolving to translation function
*/
function init(options?: InitOptions, callback?: Callback): Promise<TFunction>;
function init(callback?: Callback): Promise<TFunction>;
interface InitOptions {
/** Primary language */
lng?: string;
/** Fallback language(s) */
fallbackLng?: string | readonly string[] | FallbackLngObjList | ((code: string) => string | readonly string[] | FallbackLngObjList);
/** Debug mode */
debug?: boolean;
/** Namespaces to load */
ns?: string | readonly string[];
/** Default namespace */
defaultNS?: string | readonly string[];
/** Translation resources */
resources?: Resource;
/** Languages to preload */
preload?: readonly string[];
/** Supported languages */
supportedLngs?: readonly string[];
/** Initialize asynchronously */
initAsync?: boolean;
/** Key separator character */
keySeparator?: string | false;
/** Namespace separator character */
nsSeparator?: string | false;
/** Plural separator character */
pluralSeparator?: string;
/** Context separator character */
contextSeparator?: string;
/** Load strategy */
load?: 'all' | 'currentOnly' | 'languageOnly';
/** Interpolation options */
interpolation?: InterpolationOptions;
/** React-specific options */
react?: ReactOptions;
/** Backend options */
backend?: any;
/** Detection options */
detection?: any;
[key: string]: any;
}
interface InterpolationOptions {
/** Escape interpolated values */
escapeValue?: boolean;
/** Format function for values */
format?: FormatFunction;
/** Interpolation prefix */
prefix?: string;
/** Interpolation suffix */
suffix?: string;
/** Format separator */
formatSeparator?: string;
/** Unescape prefix */
unescapePrefix?: string;
/** Nesting prefix */
nestingPrefix?: string;
/** Nesting suffix */
nestingSuffix?: string;
/** Max replacements to prevent infinite loops */
maxReplaces?: number;
/** Skip interpolation on variables */
skipOnVariables?: boolean;
}
type Callback = (error: any, t: TFunction) => void;Usage Examples:
import i18next from "i18next";
// Basic initialization
await i18next.init({
lng: "en",
fallbackLng: "en",
resources: {
en: {
translation: {
"hello": "Hello World"
}
}
}
});
// Advanced initialization
await i18next.init({
lng: "en",
fallbackLng: ["en", "dev"],
debug: true,
ns: ["common", "navigation"],
defaultNS: "common",
keySeparator: ".",
nsSeparator: ":",
interpolation: {
escapeValue: false,
prefix: "{{",
suffix: "}}"
},
resources: {
en: {
common: { "welcome": "Welcome" },
navigation: { "home": "Home" }
}
}
});
// With callback
i18next.init({
lng: "en",
resources: { /* ... */ }
}, (err, t) => {
if (err) return console.error(err);
console.log(t("welcome"));
});Create a new i18next instance separate from the default instance.
/**
* Create a new i18next instance
* @param options - Configuration options
* @param callback - Optional callback when initialization completes
* @returns New i18next instance
*/
function createInstance(options?: InitOptions, callback?: Callback): i18n;
// Static method on i18n class
static createInstance(options?: InitOptions, callback?: Callback): i18n;Usage Examples:
import { createInstance } from "i18next";
// Create separate instance for admin panel
const adminI18n = createInstance({
lng: "en",
fallbackLng: "en",
ns: ["admin"],
resources: {
en: {
admin: {
"dashboard": "Dashboard",
"users": "Users"
}
}
}
});
// Initialize the new instance
await adminI18n.init();
console.log(adminI18n.t("dashboard")); // "Dashboard"
// Create with callback
const userI18n = createInstance({
lng: "fr",
resources: { /* ... */ }
}, (err, t) => {
console.log(t("welcome"));
});Create a clone of an existing instance, optionally with different configuration.
/**
* Clone current instance with optional configuration changes
* @param options - Configuration overrides
* @param callback - Optional callback when cloning completes
* @returns Cloned i18next instance
*/
function cloneInstance(options?: CloneOptions, callback?: Callback): i18n;
interface CloneOptions extends InitOptions {
/** Create new resource store instead of sharing */
forkResourceStore?: boolean;
}Usage Examples:
// Original instance
await i18next.init({
lng: "en",
resources: {
en: { translation: { "hello": "Hello" } },
de: { translation: { "hello": "Hallo" } }
}
});
// Clone with different language
const germanInstance = i18next.cloneInstance({
lng: "de"
});
console.log(germanInstance.t("hello")); // "Hallo"
// Clone with forked resource store
const isolatedInstance = i18next.cloneInstance({
forkResourceStore: true,
lng: "en"
});
// Modifications to isolated instance won't affect original
isolatedInstance.addResource("en", "translation", "new", "New text");
console.log(i18next.exists("new")); // false
console.log(isolatedInstance.exists("new")); // trueAccess to instance state and configuration.
interface i18n {
/** Current language */
language: string;
/** Language hierarchy for fallbacks */
languages: readonly string[];
/** Current resolved language */
resolvedLanguage?: string;
/** Current configuration options */
options: InitOptions;
/** Loaded modules */
modules: Modules;
/** Internal services */
services: Services;
/** Resource store */
store: ResourceStore;
/** Initialization status */
isInitialized: boolean;
/** Currently initializing */
isInitializing: boolean;
/** Store initialized once */
initializedStoreOnce: boolean;
/** Language initialized once */
initializedLanguageOnce: boolean;
}Usage Examples:
// Check initialization status
if (i18next.isInitialized) {
console.log(`Current language: ${i18next.language}`);
console.log(`Language hierarchy: ${i18next.languages.join(", ")}`);
}
// Access configuration
console.log(`Debug mode: ${i18next.options.debug}`);
console.log(`Namespaces: ${i18next.options.ns}`);
// Check resolved language
if (i18next.resolvedLanguage) {
console.log(`Resolved to: ${i18next.resolvedLanguage}`);
}i18next instances emit events during their lifecycle.
/**
* Add event listener
* @param event - Event name
* @param listener - Event handler function
*/
function on(event: string, listener: (...args: any[]) => void): void;
/**
* Remove event listener
* @param event - Event name
* @param listener - Optional specific handler to remove
*/
function off(event: string, listener?: (...args: any[]) => void): void;
/**
* Emit event
* @param eventName - Event name
* @param args - Event arguments
*/
function emit(eventName: string, ...args: any[]): void;Event Types:
// Initialization events
i18next.on("initialized", (options: InitOptions) => {
console.log("i18next initialized with options:", options);
});
// Resource loading events
i18next.on("loaded", (loaded: { [language: string]: { [namespace: string]: boolean } }) => {
console.log("Resources loaded:", loaded);
});
i18next.on("failedLoading", (lng: string, ns: string, msg: string) => {
console.error(`Failed loading ${lng}:${ns} - ${msg}`);
});
// Language change events
i18next.on("languageChanging", (lng: string) => {
console.log("Language changing to:", lng);
});
i18next.on("languageChanged", (lng: string) => {
console.log("Language changed to:", lng);
});
// Missing key events
i18next.on("missingKey", (lngs: readonly string[], namespace: string, key: string, res: string) => {
console.warn(`Missing key: ${key} in ${namespace} for languages: ${lngs.join(", ")}`);
});
// Resource change events
i18next.on("added", (lng: string, ns: string) => {
console.log(`Resources added: ${lng}:${ns}`);
});
i18next.on("removed", (lng: string, ns: string) => {
console.log(`Resources removed: ${lng}:${ns}`);
});Convert instance state to JSON for persistence or debugging.
/**
* Serialize instance state to JSON
* @returns Serialized instance data
*/
function toJSON(): {
options: InitOptions;
store: ResourceStore;
language: string;
languages: readonly string[];
resolvedLanguage?: string;
};Usage Examples:
// Serialize current state
const state = i18next.toJSON();
console.log(JSON.stringify(state, null, 2));
// Could be used for debugging or state persistence
const serializedState = {
options: state.options,
currentLanguage: state.language,
loadedLanguages: state.languages,
resources: state.store.data
};