-
Notifications
You must be signed in to change notification settings - Fork 1k
/
node.ts
60 lines (50 loc) · 1.72 KB
/
node.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
import { existsSync } from 'fs';
import { readFileSync } from 'fs-extra';
import { resolve } from 'path';
import type typescript from 'typescript';
interface NodeModuleWithCompile extends NodeJS.Module {
_compile?(code: string, filename: string): any;
}
/**
* @see https://github.com/ionic-team/stencil/blob/HEAD/src/compiler/sys/node-require.ts
*/
export const requireTS = (ts: typeof typescript, p: string): unknown => {
const id = resolve(p);
delete require.cache[id];
require.extensions['.ts'] = (module: NodeModuleWithCompile, fileName: string) => {
let sourceText = readFileSync(fileName, 'utf8');
if (fileName.endsWith('.ts')) {
const tsResults = ts.transpileModule(sourceText, {
fileName,
compilerOptions: {
module: ts.ModuleKind.CommonJS,
moduleResolution: ts.ModuleResolutionKind.NodeJs,
esModuleInterop: true,
strict: true,
target: ts.ScriptTarget.ES2017,
},
reportDiagnostics: true,
});
sourceText = tsResults.outputText;
} else {
// quick hack to turn a modern es module
// into and old school commonjs module
sourceText = sourceText.replace(/export\s+\w+\s+(\w+)/gm, 'exports.$1');
}
module._compile?.(sourceText, fileName);
};
const m = require(id); // eslint-disable-line @typescript-eslint/no-var-requires
delete require.extensions['.ts'];
return m;
};
export function resolveNode(root: string, ...pathSegments: string[]): string | null {
try {
return require.resolve(pathSegments.join('/'), { paths: [root] });
} catch (e) {
const path = [root, 'node_modules', ...pathSegments].join('/');
if (existsSync(path)) {
return path;
}
return null;
}
}