/
update-imports.ts
237 lines (210 loc) · 5.93 KB
/
update-imports.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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import {
applyChangesToString,
ChangeType,
getProjects,
getWorkspaceLayout,
joinPathFragments,
ProjectConfiguration,
StringChange,
Tree,
visitNotIgnoredFiles,
writeJson,
} from '@nrwl/devkit';
import { getImportPath } from 'nx/src/utils/path';
import * as ts from 'typescript';
import { getRootTsConfigPathInTree } from '../../../utilities/typescript';
import { findNodes } from 'nx/src/utils/typescript';
import { NormalizedSchema } from '../schema';
import { normalizeSlashes } from './utils';
import { relative } from 'path';
import { parse } from 'jsonc-parser';
/**
* Updates all the imports in the workspace and modifies the tsconfig appropriately.
*
* @param schema The options provided to the schematic
*/
export function updateImports(
tree: Tree,
schema: NormalizedSchema,
project: ProjectConfiguration
) {
if (project.projectType === 'application') {
// These shouldn't be imported anywhere?
return;
}
const { npmScope, libsDir } = getWorkspaceLayout(tree);
const projects = getProjects(tree);
// use the source root to find the from location
// this attempts to account for libs that have been created with --importPath
const tsConfigPath = getRootTsConfigPathInTree(tree);
let tsConfig: any;
let fromPath: string;
if (tree.exists(tsConfigPath)) {
const tsConfigRawContents = tree.read(tsConfigPath).toString('utf-8');
tsConfig = (() => {
try {
return JSON.parse(tsConfigRawContents);
} catch {
return parse(tsConfigRawContents);
}
})();
fromPath = Object.keys(tsConfig.compilerOptions.paths).find((path) =>
tsConfig.compilerOptions.paths[path].some((x) =>
x.startsWith(project.sourceRoot)
)
);
}
const projectRef = {
from:
fromPath ||
normalizeSlashes(
getImportPath(
npmScope,
project.root.slice(libsDir.length).replace(/^\/|\\/, '')
)
),
to: schema.importPath,
};
if (schema.updateImportPath) {
const replaceProjectRef = new RegExp(projectRef.from, 'g');
for (const [name, definition] of Array.from(projects.entries())) {
if (name === schema.projectName) {
continue;
}
visitNotIgnoredFiles(tree, definition.root, (file) => {
const contents = tree.read(file, 'utf-8');
replaceProjectRef.lastIndex = 0;
if (!replaceProjectRef.test(contents)) {
return;
}
updateImportPaths(tree, file, projectRef.from, projectRef.to);
});
}
}
const projectRoot = {
from: project.root,
to: schema.relativeToRootDestination,
};
if (tsConfig) {
const path = tsConfig.compilerOptions.paths[projectRef.from] as string[];
if (!path) {
throw new Error(
[
`unable to find "${projectRef.from}" in`,
`${tsConfigPath} compilerOptions.paths`,
].join(' ')
);
}
const updatedPath = path.map((x) =>
joinPathFragments(projectRoot.to, relative(projectRoot.from, x))
);
if (schema.updateImportPath) {
tsConfig.compilerOptions.paths[projectRef.to] = updatedPath;
delete tsConfig.compilerOptions.paths[projectRef.from];
} else {
tsConfig.compilerOptions.paths[projectRef.from] = updatedPath;
}
writeJson(tree, tsConfigPath, tsConfig);
}
}
/**
* Changes imports in a file from one import to another
*/
function updateImportPaths(tree: Tree, path: string, from: string, to: string) {
const contents = tree.read(path, 'utf-8');
const sourceFile = ts.createSourceFile(
path,
contents,
ts.ScriptTarget.Latest,
true
);
// Apply changes on the various types of imports
const newContents = applyChangesToString(contents, [
...updateImportDeclarations(sourceFile, from, to),
...updateDynamicImports(sourceFile, from, to),
]);
tree.write(path, newContents);
}
/**
* Update the module specifiers on static imports
*/
function updateImportDeclarations(
sourceFile: ts.SourceFile,
from: string,
to: string
): StringChange[] {
const importDecls = findNodes(
sourceFile,
ts.SyntaxKind.ImportDeclaration
) as ts.ImportDeclaration[];
const changes: StringChange[] = [];
for (const { moduleSpecifier } of importDecls) {
if (ts.isStringLiteral(moduleSpecifier)) {
changes.push(...updateModuleSpecifier(moduleSpecifier, from, to));
}
}
return changes;
}
/**
* Update the module specifiers on dynamic imports and require statements
*/
function updateDynamicImports(
sourceFile: ts.SourceFile,
from: string,
to: string
): StringChange[] {
const expressions = findNodes(
sourceFile,
ts.SyntaxKind.CallExpression
) as ts.CallExpression[];
const changes: StringChange[] = [];
for (const { expression, arguments: args } of expressions) {
const moduleSpecifier = args[0];
// handle dynamic import statements
if (
expression.kind === ts.SyntaxKind.ImportKeyword &&
moduleSpecifier &&
ts.isStringLiteral(moduleSpecifier)
) {
changes.push(...updateModuleSpecifier(moduleSpecifier, from, to));
}
// handle require statements
if (
ts.isIdentifier(expression) &&
expression.text === 'require' &&
moduleSpecifier &&
ts.isStringLiteral(moduleSpecifier)
) {
changes.push(...updateModuleSpecifier(moduleSpecifier, from, to));
}
}
return changes;
}
/**
* Replace the old module specifier with a the new path
*/
function updateModuleSpecifier(
moduleSpecifier: ts.StringLiteral,
from: string,
to: string
): StringChange[] {
if (
moduleSpecifier.text === from ||
moduleSpecifier.text.startsWith(`${from}/`)
) {
return [
{
type: ChangeType.Delete,
start: moduleSpecifier.getStart() + 1,
length: moduleSpecifier.text.length,
},
{
type: ChangeType.Insert,
index: moduleSpecifier.getStart() + 1,
text: moduleSpecifier.text.replace(new RegExp(from, 'g'), to),
},
];
} else {
return [];
}
}