UNPKG

1.75 kBJavaScriptView Raw
1const resolve = require('path').resolve
2
3const loadJSConfig = getAttemptModuleRequireFn(function onFail(configPath, requirePath) {
4 console.log(`Unable to find JS config at "${configPath}". Attempted to require as "${requirePath}"`)
5 // log.error({
6 // message: colors.red(`Unable to find JS config at "${configPath}". Attempted to require as "${requirePath}"`),
7 // ref: 'unable-to-find-config',
8 // })
9 return undefined
10})
11
12/**
13 * Determines the proper require path for a module. If the path starts with `.` then it is resolved with process.cwd()
14 * @param {String} moduleName The module path
15 * @return {String} the module path to require
16 */
17function getModuleRequirePath(moduleName) {
18 return moduleName[0] === '.' ? resolve(process.cwd(), moduleName) : moduleName
19}
20
21function getAttemptModuleRequireFn(onFail) {
22 return function attemptModuleRequire(moduleName) {
23 const requirePath = getModuleRequirePath(moduleName)
24 try {
25 return requireDefaultFromModule(requirePath)
26 } catch (e) {
27 if (e.constructor.name === 'SyntaxError') {
28 throw e
29 }
30 return onFail(moduleName, requirePath)
31 }
32 }
33}
34
35/**
36 * Requires the given module and returns the `default` if it's an `__esModule`
37 * @param {String} modulePath The module to require
38 * @return {*} The required module (or it's `default` if it's an `__esModule`)
39 */
40function requireDefaultFromModule(modulePath) {
41 /* eslint global-require:0,import/no-dynamic-require:0 */
42 const mod = require(modulePath)
43 if (mod.__esModule) {
44 return mod.default
45 } else {
46 return mod
47 }
48}
49
50function loadConfig(configPath) {
51 // potentially load other types of config files
52 return loadJSConfig(configPath)
53}
54
55module.exports.loadConfig = loadConfig