-
-
Notifications
You must be signed in to change notification settings - Fork 506
/
require-search.ts
32 lines (28 loc) · 1.06 KB
/
require-search.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
import debug from 'debug';
import path from 'path';
const d = debug('electron-forge:require-search');
export function requireSearchRaw<T>(relativeTo: string, paths: string[]): T | null {
const testPaths = paths
.concat(paths.map(mapPath => path.resolve(relativeTo, mapPath)))
.concat(paths.map(mapPath => path.resolve(relativeTo, 'node_modules', mapPath)));
d('searching', testPaths, 'relative to', relativeTo);
for (const testPath of testPaths) {
try {
d('testing', testPath);
// eslint-disable-next-line global-require, import/no-dynamic-require
return require(testPath);
} catch (err) {
// Ignore the error
}
}
d('failed to find a module in', testPaths);
return null;
}
export type PossibleModule<T> = {
default?: T;
} & T;
// eslint-disable-next-line arrow-parens
export default <T>(relativeTo: string, paths: string[]): T | null => {
const result = requireSearchRaw<PossibleModule<T>>(relativeTo, paths);
return typeof result === 'object' && result && result.default ? result.default : result as (T | null);
};