explore-config
Version:
Explore multi-format JavaScript module configuration
56 lines (52 loc) • 1.69 kB
JavaScript
;
var crossImport = require('cross-import');
var fs = require('fs');
var path = require('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 = path.resolve(options.cwd || '', name);
if (fs.existsSync(resolvedPath)) {
foundConfigPath = resolvedPath;
foundBasename = path.parse(name).base;
}
} else {
for (const eachExtension of options.extensions){
const eachBasename = name.endsWith('.' + eachExtension) ? name : name + '.' + eachExtension;
const eachPath = path.resolve(options.cwd || '', eachBasename);
if (fs.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;
}
module.exports = exploreConfig;