-
Notifications
You must be signed in to change notification settings - Fork 771
/
module-graph.ts
49 lines (36 loc) · 1.54 KB
/
module-graph.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
import { BuildCtx, Config, ModuleGraph } from '../../../declarations/index';
import { normalizePath, pathJoin } from '../../util';
import * as ts from 'typescript';
export function moduleGraph(config: Config, buildCtx: BuildCtx): ts.TransformerFactory<ts.SourceFile> {
return (transformContext) => {
function visitImport(moduleGraph: ModuleGraph, dirPath: string, importNode: ts.ImportDeclaration) {
if (importNode.moduleSpecifier) {
let importPath = importNode.moduleSpecifier.getText().replace(/\'|\"|\`/g, '');
if (importPath.startsWith('.') || importPath.startsWith('/')) {
importPath = pathJoin(config, dirPath, importPath);
}
moduleGraph.importPaths.push(importPath);
}
return importNode;
}
function visit(moduleGraph: ModuleGraph, dirPath: string, node: ts.Node): ts.VisitResult<ts.Node> {
switch (node.kind) {
case ts.SyntaxKind.ImportDeclaration:
return visitImport(moduleGraph, dirPath, node as ts.ImportDeclaration);
default:
return ts.visitEachChild(node, (node) => {
return visit(moduleGraph, dirPath, node);
}, transformContext);
}
}
return (tsSourceFile) => {
const moduleGraph: ModuleGraph = {
filePath: normalizePath(tsSourceFile.fileName),
importPaths: []
};
const dirPath = config.sys.path.dirname(tsSourceFile.fileName);
buildCtx.moduleGraph.push(moduleGraph);
return visit(moduleGraph, dirPath, tsSourceFile) as ts.SourceFile;
};
};
}