-
Notifications
You must be signed in to change notification settings - Fork 18
/
paths.ts
66 lines (54 loc) · 1.63 KB
/
paths.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
64
65
66
import * as ts from 'typescript'
import {resolve} from '../modules/resolver'
export interface ImportDependency {
source: string
position: number
}
export const PathTransform = (
rootDir: string,
options: ts.CompilerOptions,
host: ts.ModuleResolutionHost,
dependencies?: Map<string, ImportDependency[]>|null
): ts.TransformerFactory<ts.SourceFile> =>
(context: ts.TransformationContext) =>
(source: ts.SourceFile) => {
if(!options.baseUrl && !dependencies) {
return source
}
return ts.visitNode(source, rootNode =>
ts.visitEachChild(rootNode, node => {
if(!ts.isImportDeclaration(node) && !ts.isExportDeclaration(node)) {
return node
}
const specifier = node.moduleSpecifier
if(!specifier || !ts.isStringLiteral(specifier)) {
return node
}
const resolved = resolve(source.fileName, specifier.text, rootDir, options, host)
if(dependencies) {
const deps = dependencies.get(source.fileName)
const dep = {
source: resolved,
position: specifier.pos
}
if(deps) {
deps.push(dep)
}
else {
dependencies.set(source.fileName, [dep])
}
}
if((dependencies || options.baseUrl) && resolved !== specifier.text) {
const {decorators, modifiers} = node
const literal = ts.createLiteral(resolved)
if(ts.isExportDeclaration(node)) {
return ts.updateExportDeclaration(node, decorators, modifiers, node.exportClause, literal)
}
else {
return ts.updateImportDeclaration(node, decorators, modifiers, node.importClause, literal)
}
}
return node
}, context)
)
}