-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (102 loc) · 2.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Node's `require` with a few extra features:
* - You can specify additional folders in which to search for modules
* - You can specify a module prefix
* @module load-module
* @example
* > const loadModule = require('load-module')
*
* > loadModule('react-dom')
*
* > loadModule('dom', { prefix: 'react-' })
*
* > loadModule('something.js', { paths: '.' })
*
* > loadModule('something.js', { paths: [ '.', '~/my-modules' ] })
*/
/**
* @alias module:load-module
* @param {string} - The module name, directory or file to load.
* @param {object} [options]
* @param {string} [options.prefix] - Also attempt to load the given module name with this prefix.
* @param {string|string[]} [options.paths] - One or more additional directories in which to search for modules.
*/
function loadModule (request, options) {
if (typeof request !== 'string') {
throw new Error('request expected')
}
options = options || {}
const arrayify = require('array-back')
const prefix = options.prefix
const paths = options.paths ? arrayify(options.paths) : undefined
const origModulePaths = module.paths
if (paths && paths.length) {
module.paths = module.paths.concat(paths)
}
let output = null
if (prefix) {
try {
output = loadModule(`${prefix}${request}`, { paths })
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
output = loadModule(request, { paths })
} else {
throw err
}
}
} else {
output = loadAsLocalPath(request, { paths })
if (output === null) {
output = loadAsRegularRequire(request, { paths })
}
if (output === null) {
output = tryEachPath(request, { paths })
}
}
module.paths = origModulePaths
if (output === null) {
const err = new Error('Cannot find ' + request)
err.code = 'MODULE_NOT_FOUND'
throw err
} else {
return output
}
}
function loadAsLocalPath (request, options) {
const path = require('path')
let output
try {
output = require(path.resolve(request), options)
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
output = null
} else {
throw err
}
}
return output
}
function loadAsRegularRequire (request, options) {
let output
try {
output = require(require.resolve(request, options))
} catch (err) {
if (err.code === 'MODULE_NOT_FOUND') {
output = null
} else {
throw err
}
}
return output
}
function tryEachPath (request, options) {
const path = require('path')
let output = null
for (const p of options.paths || []) {
const fullPath = path.resolve(p, request)
output = loadAsRegularRequire(fullPath)
if (output !== null) break
}
return output
}
module.exports = loadModule