refactor: reconstruct language files into multi-file structures (#4683)
* refactor: reconstruct language files into multi-file structures * chore: typo
This commit is contained in:
@@ -19,12 +19,14 @@ const i18n = createI18n({
|
||||
messages: {},
|
||||
});
|
||||
|
||||
const modules = import.meta.glob('./langs/*.json');
|
||||
const modules = import.meta.glob('./langs/**/*.json');
|
||||
|
||||
const { setSimpleLocale } = useSimpleLocale();
|
||||
|
||||
const localesMap = loadLocalesMap(modules);
|
||||
|
||||
const localesMap = loadLocalesMapFromDir(
|
||||
/\.\/langs\/([^/]+)\/(.*)\.json$/,
|
||||
modules,
|
||||
);
|
||||
let loadMessages: LoadMessageFn;
|
||||
|
||||
/**
|
||||
@@ -40,6 +42,48 @@ function loadLocalesMap(modules: Record<string, () => Promise<unknown>>) {
|
||||
localesMap[key] = loadLocale as ImportLocaleFn;
|
||||
}
|
||||
}
|
||||
return localesMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load locale modules with directory structure
|
||||
* @param regexp - Regular expression to match language and file names
|
||||
* @param modules - The modules object containing paths and import functions
|
||||
* @returns A map of locales to their corresponding import functions
|
||||
*/
|
||||
function loadLocalesMapFromDir(
|
||||
regexp: RegExp,
|
||||
modules: Record<string, () => Promise<unknown>>,
|
||||
): Record<Locale, ImportLocaleFn> {
|
||||
const localesRaw: Record<Locale, Record<string, () => Promise<unknown>>> = {};
|
||||
const localesMap: Record<Locale, ImportLocaleFn> = {};
|
||||
|
||||
// Iterate over the modules to extract language and file names
|
||||
for (const path in modules) {
|
||||
const match = path.match(regexp);
|
||||
if (match) {
|
||||
const [_, locale, fileName] = match;
|
||||
if (locale && fileName) {
|
||||
if (!localesRaw[locale]) {
|
||||
localesRaw[locale] = {};
|
||||
}
|
||||
if (modules[path]) {
|
||||
localesRaw[locale][fileName] = modules[path];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert raw locale data into async import functions
|
||||
for (const [locale, files] of Object.entries(localesRaw)) {
|
||||
localesMap[locale] = async () => {
|
||||
const messages: Record<string, any> = {};
|
||||
for (const [fileName, importFn] of Object.entries(files)) {
|
||||
messages[fileName] = ((await importFn()) as any)?.default;
|
||||
}
|
||||
return { default: messages };
|
||||
};
|
||||
}
|
||||
|
||||
return localesMap;
|
||||
}
|
||||
@@ -93,4 +137,10 @@ async function loadLocaleMessages(lang: SupportedLanguagesType) {
|
||||
return setI18nLanguage(lang);
|
||||
}
|
||||
|
||||
export { i18n, loadLocaleMessages, loadLocalesMap, setupI18n };
|
||||
export {
|
||||
i18n,
|
||||
loadLocaleMessages,
|
||||
loadLocalesMap,
|
||||
loadLocalesMapFromDir,
|
||||
setupI18n,
|
||||
};
|
||||
|
Reference in New Issue
Block a user