explore-config
Version:
Explore multi-format JavaScript module configuration
54 lines (51 loc) • 1.68 kB
JavaScript
import crossImport from 'cross-import';
import { existsSync } from 'fs';
import { resolve, parse } from 'path';
function exploreConfig(name, options = {}) {
options = Object.assign({
extensions: [
'js',
'mjs',
'ts',
'cjs',
'cts',
'mts'
],
resolvedKeys: [
'config',
'default'
]
}, options);
let config;
// try to find the config file with the given name and options.extensions
let foundConfigPath;
let foundBasename;
if (options.extensions.find((ext)=>name.endsWith('.' + ext))) {
const resolvedPath = resolve(options.cwd || '', name);
if (existsSync(resolvedPath)) {
foundConfigPath = resolvedPath;
foundBasename = parse(name).base;
}
} else {
for (const eachExtension of options.extensions){
const eachBasename = name.endsWith('.' + eachExtension) ? name : name + '.' + eachExtension;
const eachPath = resolve(options.cwd || '', eachBasename);
if (existsSync(eachPath)) {
foundConfigPath = eachPath;
foundBasename = eachBasename;
break;
}
}
}
if (foundConfigPath) {
const configModule = crossImport(foundConfigPath);
for (const eachResolvedKey of options.resolvedKeys){
config = configModule[eachResolvedKey];
if (config) break;
}
if (!config) config = configModule;
options?.found?.(foundBasename, foundConfigPath);
}
return config;
}
export { exploreConfig as default };