-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathresolve.js
56 lines (47 loc) · 1.17 KB
/
resolve.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
import fs from 'fs'
import { createRequire } from 'module'
import path from 'path'
const require = createRequire(import.meta.url)
/**
* Returns the full path to the requested resource, if available
*
* @param {string} filePath
* @param {string} [module]
*/
export default function resolve (filePath, module = '') {
if (module) {
filePath = path.join(module, filePath)
}
const paths = [
path.join(process.cwd(), filePath),
path.join(process.cwd(), 'node_modules', filePath),
requireResolve(filePath)
]
if (module) {
// simulate node's node_modules lookup
for (let i = 0; i < process.cwd().split(path.sep).length; i++) {
const dots = new Array(i).fill('..')
paths.push(
path.resolve(
path.join(process.cwd(), ...dots, 'node_modules', filePath)
)
)
}
}
const resourcePath = paths.find(path => fs.existsSync(path))
if (!resourcePath) {
throw new Error(`Could not load ${filePath}`)
}
return resourcePath
}
/**
* @param {string} filePath
*/
function requireResolve (filePath) {
try {
return require.resolve(filePath)
} catch (error) {
// ignore error
return filePath
}
}