config.ts
Overview
The config.ts file is responsible for configuring the internationalization (i18n) setup of the application using the i18next framework integrated with React through react-i18next. It imports multiple language translation resources, organizes them into a structured resource object, and initializes the i18n instance with language detection and fallback mechanisms.
Additionally, the file processes translation JSON objects by flattening nested keys and generates a comprehensive translation table used elsewhere in the application for managing and referencing translations efficiently.
Detailed Explanation
Imported Modules and Resources
i18next: Core internationalization framework.
i18next-browser-languagedetector: Plugin for detecting user language preferences from the browser environment.
initReactI18next: React binding for i18next, enabling hooks and HOCs for translation.
LanguageAbbreviation: Enum or constant mapping of language codes used in the app.
Translation resources: Language-specific translation JSON imports (e.g.,
translation_en,translation_de, etc.).Utility functions from
./until:flattenObject: Flattens nested translation objects into dot-notated key-value pairs.createTranslationTable: Creates a structured table of translations across multiple languages.
Constants and Data Structures
resources
An object mapping language abbreviations to their respective translation JSON objects. It follows the shape required by i18next:
const resources = {
[LanguageAbbreviation.En]: translation_en,
[LanguageAbbreviation.Zh]: translation_zh,
// ... other languages
};
This structure is used directly as the resources property during i18n initialization.
Flattened Translation Objects
Each imported translation JSON is converted into a flattened object using flattenObject. Flattening transforms nested translation keys like:
{
"home": {
"title": "Welcome"
}
}
into:
{
"home.title": "Welcome"
}
This flattening is beneficial for creating cross-language translation tables and easier key management.
Example:
const enFlattened = flattenObject(translation_en);
// Similar for other languages
translationTable
Created by passing arrays of flattened translation objects and their corresponding language names into createTranslationTable. This table supports features such as:
Side-by-side comparison of translations.
Lookup and management of translation keys across languages.
Facilitating UI components that require multi-language data.
Example usage elsewhere could be to display a translation management interface or to validate missing translations.
export const translationTable = createTranslationTable(
[enFlattened, viFlattened, ruFlattened, ...],
['English', 'Vietnamese', 'Rus', ...],
);
i18next Initialization
The i18n instance is initialized with:
Plugins:
initReactI18next: Integrates i18next with React.LanguageDetector: Detects the user's preferred language (uses localStorage key'lng').
Options:
detection.lookupLocalStorage: Specifies localStorage key to check for language preference.supportedLngs: Array of supported languages derived fromLanguageAbbreviation.resources: The language resource object described above.fallbackLng: Default language set to English ('en') if detection fails.interpolation.escapeValue: Disabled to prevent double escaping in React.
i18n
.use(initReactI18next)
.use(LanguageDetector)
.init({
detection: {
lookupLocalStorage: 'lng',
},
supportedLngs: Object.values(LanguageAbbreviation),
resources,
fallbackLng: 'en',
interpolation: {
escapeValue: false,
},
});
The configured i18n instance is then exported as the default export of the file.
Usage Examples
Accessing Translations in React Components
By importing the default i18n instance (or more commonly using the useTranslation hook from react-i18next), components can render localized text:
import React from 'react';
import { useTranslation } from 'react-i18next';
export function WelcomeMessage() {
const { t } = useTranslation();
return <h1>{t('home.title')}</h1>;
}
Translation Table Usage
The exported translationTable can be used in admin panels or developer tools to show translations side-by-side for review or editing.
Implementation Details and Algorithms
Flattening Translations: The flattening algorithm recursively walks through nested translation JSON objects and converts them into single-level key-value pairs using dot notation, which simplifies access and comparison.
Translation Table Creation: Combines multiple flattened translation objects with their language labels into a tabular format that aligns keys across languages.
Language Detection: Uses browser preferences and localStorage to detect and persist user language settings.
Interaction with Other Files
Translation JSON files (
./de,./en, etc.): Contain the actual localized string data.Utility file
./until: Provides helper functionsflattenObjectandcreateTranslationTablecritical for translation data manipulation.Constants file
@/constants/common: Supplies theLanguageAbbreviationenum used to identify languages systematically.React components: Consume the configured i18n instance for rendering localized content.
Potential Admin or Developer Tools: Use
translationTableto manage or audit translations.
Diagram: Flowchart of Main Functions and Relationships
flowchart TD
A[Translation JSON Imports] --> B[flattenObject]
B --> C[Flattened Translation Objects]
C --> D[createTranslationTable]
D --> E[translationTable Export]
A --> F[resources Object]
F --> G[i18n.init]
H[LanguageAbbreviation] --> F
I[i18next, LanguageDetector, initReactI18next Plugins] --> G
G --> J[Default Export: i18n Instance]
Summary
The config.ts file centralizes the i18n configuration for the application by:
Importing and structuring language resources.
Flattening translation objects for efficient key management.
Creating a translation table for cross-language reference.
Initializing i18next with React and browser language detection support.
Exporting the configured i18n instance for use throughout the app.
This setup ensures scalable, maintainable, and user-friendly internationalization support.