-
Notifications
You must be signed in to change notification settings - Fork 27.4k
/
Copy pathresolve-from.ts
55 lines (47 loc) · 1.22 KB
/
resolve-from.ts
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
// source: https://github.com/sindresorhus/resolve-from
import path from 'path'
import isError from './is-error'
import { realpathSync } from './realpath'
const Module = require('module')
export const resolveFrom = (
fromDirectory: string,
moduleId: string,
silent?: boolean
) => {
if (typeof fromDirectory !== 'string') {
throw new TypeError(
`Expected \`fromDir\` to be of type \`string\`, got \`${typeof fromDirectory}\``
)
}
if (typeof moduleId !== 'string') {
throw new TypeError(
`Expected \`moduleId\` to be of type \`string\`, got \`${typeof moduleId}\``
)
}
try {
fromDirectory = realpathSync(fromDirectory)
} catch (error: unknown) {
if (isError(error) && error.code === 'ENOENT') {
fromDirectory = path.resolve(fromDirectory)
} else if (silent) {
return
} else {
throw error
}
}
const fromFile = path.join(fromDirectory, 'noop.js')
const resolveFileName = () =>
Module._resolveFilename(moduleId, {
id: fromFile,
filename: fromFile,
paths: Module._nodeModulePaths(fromDirectory),
})
if (silent) {
try {
return resolveFileName()
} catch (error) {
return
}
}
return resolveFileName()
}