-
-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
interpret-require.ts
63 lines (49 loc) · 1.53 KB
/
interpret-require.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
56
57
58
59
60
61
62
63
import { getInterpretedFileWithExt } from './interpret-files';
let registered = false;
export function interopRequireDefault(filePath: string) {
if (registered === false) {
// eslint-disable-next-line global-require
const { register } = require('esbuild-register/dist/node');
registered = true;
register({
target: `node${process.version.slice(1)}`,
format: 'cjs',
hookIgnoreNodeModules: false,
tsconfigRaw: `{
"compilerOptions": {
"strict": false,
"skipLibCheck": true,
},
}`,
});
}
// eslint-disable-next-line import/no-dynamic-require,global-require
const result = require(filePath);
const isES6DefaultExported =
typeof result === 'object' && result !== null && typeof result.default !== 'undefined';
return isES6DefaultExported ? result.default : result;
}
function getCandidate(paths: string[]) {
for (let i = 0; i < paths.length; i += 1) {
const candidate = getInterpretedFileWithExt(paths[i]);
if (candidate) {
return candidate;
}
}
return undefined;
}
export function serverRequire(filePath: string | string[]) {
const candidatePath = serverResolve(filePath);
if (!candidatePath) {
return null;
}
return interopRequireDefault(candidatePath);
}
export function serverResolve(filePath: string | string[]): string | null {
const paths = Array.isArray(filePath) ? filePath : [filePath];
const existingCandidate = getCandidate(paths);
if (!existingCandidate) {
return null;
}
return existingCandidate.path;
}