UNPKG

2.88 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.renamePackageImports = void 0;
4const tslib_1 = require("tslib");
5const ts = require("typescript");
6const schematics_1 = require("@angular-devkit/schematics");
7const workspace_1 = require("../workspace");
8const visit_not_ignored_files_1 = require("./visit-not-ignored-files");
9const ast_utils_1 = require("../ast-utils");
10const core_1 = require("@angular-devkit/core");
11/**
12 * Updates all the imports found in the workspace
13 *
14 * @param packageNameMapping The packageNameMapping provided to the schematic
15 */
16function renamePackageImports(packageNameMapping) {
17 return (tree, _context) => tslib_1.__awaiter(this, void 0, void 0, function* () {
18 const workspace = yield (0, workspace_1.getWorkspace)(tree);
19 const rules = [];
20 workspace.projects.forEach((project) => {
21 rules.push((0, visit_not_ignored_files_1.visitNotIgnoredFiles)((file) => {
22 if (!/([jt])sx?$/.test(file)) {
23 return;
24 }
25 const contents = tree.read(file).toString('utf-8');
26 const fileIncludesPackageToRename = Object.keys(packageNameMapping).some((packageName) => {
27 return contents.includes(packageName);
28 });
29 if (!fileIncludesPackageToRename) {
30 return;
31 }
32 const astSource = ts.createSourceFile(file, contents, ts.ScriptTarget.Latest, true);
33 const changes = Object.entries(packageNameMapping)
34 .map(([packageName, newPackageName]) => {
35 const nodes = (0, ast_utils_1.findNodes)(astSource, ts.SyntaxKind.ImportDeclaration);
36 return nodes
37 .filter((node) => {
38 return (
39 // remove quotes from module name
40 node.moduleSpecifier.getText().slice(1).slice(0, -1) ===
41 packageName);
42 })
43 .map((node) => new ast_utils_1.ReplaceChange(file, node.moduleSpecifier.getStart(), node.moduleSpecifier.getText(), `'${newPackageName}'`));
44 })
45 // .flatMap()/.flat() is not available? So, here's a flat poly
46 .reduce((acc, val) => acc.concat(val), []);
47 // if the reference to packageName was in fact an import statement
48 if (changes.length > 0) {
49 // update the file in the tree
50 (0, ast_utils_1.insert)(tree, file, changes);
51 }
52 }, (0, core_1.normalize)(project.root)));
53 });
54 return (0, schematics_1.chain)(rules);
55 });
56}
57exports.renamePackageImports = renamePackageImports;
58//# sourceMappingURL=rename-package-imports.js.map
\No newline at end of file