1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | exports.insertImport = void 0;
|
4 | const insert_statement_1 = require("./insert-statement");
|
5 | const devkit_1 = require("@nrwl/devkit");
|
6 | const typescript_1 = require("typescript");
|
7 | function insertImport(tree, path, name, modulePath) {
|
8 | const contents = tree.read(path, 'utf-8');
|
9 | const sourceFile = (0, typescript_1.createSourceFile)(path, contents, typescript_1.ScriptTarget.ESNext);
|
10 | const importStatements = sourceFile.statements.filter(typescript_1.isImportDeclaration);
|
11 | const existingImport = importStatements.find((statement) => (0, typescript_1.isStringLiteral)(statement.moduleSpecifier) &&
|
12 | statement.moduleSpecifier
|
13 | .getText(sourceFile)
|
14 | .replace(/['"`]/g, '')
|
15 | .trim() === modulePath &&
|
16 | statement.importClause.namedBindings &&
|
17 | (0, typescript_1.isNamedImports)(statement.importClause.namedBindings));
|
18 | if (!existingImport) {
|
19 | (0, insert_statement_1.insertStatement)(tree, path, `import { ${name} } from '${modulePath}';`);
|
20 | return;
|
21 | }
|
22 |
|
23 | const namedImports = existingImport.importClause
|
24 | .namedBindings;
|
25 | const index = namedImports.getEnd() - 1;
|
26 | let text;
|
27 | if (namedImports.elements.hasTrailingComma) {
|
28 | text = `${name},`;
|
29 | }
|
30 | else {
|
31 | text = `,${name}`;
|
32 | }
|
33 | const newContents = (0, devkit_1.applyChangesToString)(contents, [
|
34 | {
|
35 | type: devkit_1.ChangeType.Insert,
|
36 | index,
|
37 | text,
|
38 | },
|
39 | ]);
|
40 | tree.write(path, newContents);
|
41 | }
|
42 | exports.insertImport = insertImport;
|
43 |
|
\ | No newline at end of file |