-
Notifications
You must be signed in to change notification settings - Fork 36
/
collect-imports.js
101 lines (93 loc) · 3.02 KB
/
collect-imports.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import {
hasDefaultImport,
hasNamedImport,
hasAggregatingImport,
hasSideEffectImport,
} from '../../utils/imports.js';
import { isBareModuleSpecifier } from '../../utils/index.js';
/**
* COLLECT-IMPORTS
*
* Collects a modules imports so that declarations can later be resolved to their module/package.
*/
export function collectImportsPlugin() {
const files = {};
let currModuleImports;
return {
name: 'CORE - IMPORTS',
collectPhase({ts, node}) {
if(node.kind === ts.SyntaxKind.SourceFile) {
/**
* Create an empty array for each module we visit
*/
files[node.fileName] = [];
currModuleImports = files[node.fileName];
}
/**
* @example import defaultExport from 'foo';
*/
if (hasDefaultImport(node)) {
const importTemplate = {
name: node.importClause.name.text,
kind: 'default',
importPath: node.moduleSpecifier.text,
isBareModuleSpecifier: isBareModuleSpecifier(node.moduleSpecifier.text),
isTypeOnly: !!node?.importClause?.isTypeOnly
};
currModuleImports.push(importTemplate);
}
/**
* @example import { export1, export2 } from 'foo';
* @example import { export1 as alias1 } from 'foo';
* @example import { export1, export2 as alias2 } from 'foo';
*/
if (hasNamedImport(node)) {
node.importClause.namedBindings.elements.forEach((element) => {
const importTemplate = {
name: element.name.text,
kind: 'named',
importPath: node.moduleSpecifier.text,
isBareModuleSpecifier: isBareModuleSpecifier(node.moduleSpecifier.text),
isTypeOnly: !!node?.importClause?.isTypeOnly
};
currModuleImports.push(importTemplate);
});
}
/**
* @example import * as name from './my-module.js';
*/
if (hasAggregatingImport(node)) {
const importTemplate = {
name: node.importClause.namedBindings.name.text,
kind: 'aggregate',
importPath: node.moduleSpecifier.text,
isBareModuleSpecifier: isBareModuleSpecifier(node.moduleSpecifier.text),
isTypeOnly: !!node?.importClause?.isTypeOnly
};
currModuleImports.push(importTemplate);
}
/**
* @example import './my-module.js';
*/
if(hasSideEffectImport(node)) {
const importTemplate = {
kind: 'side-effect',
importPath: node.moduleSpecifier.text,
isBareModuleSpecifier: isBareModuleSpecifier(node.moduleSpecifier.text),
isTypeOnly: false
};
currModuleImports.push(importTemplate);
}
},
analyzePhase({ts, node, context}) {
if(node.kind === ts.SyntaxKind.SourceFile) {
/** Makes the imports available on the context object for a given module */
context.imports = files[node.fileName];
}
},
packageLinkPhase({context}) {
/** Reset */
context.imports = [];
}
}
}