Created
September 1, 2022 20:25
-
-
Save manbearwiz/5ec10b964c3fa262594a6f7ce685bfea to your computer and use it in GitHub Desktop.
Angular schematic function to remove import from file. Inspired by `insertImport` from the angular cli repo.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { findNodes } from '@schematics/angular/utility/ast-utils'; | |
import { NoopChange, RemoveChange } from '@schematics/angular/utility/change'; | |
import { | |
ImportSpecifier, | |
isStringLiteral, | |
SourceFile, | |
SyntaxKind, | |
} from 'typescript'; | |
/** | |
* Remove symbol import. Remove entire import statement if it would be left empty | |
* @param fileToEdit (file we want to remove import from) | |
* @param symbolName (item to remove) | |
* @param fileName (path to the file) | |
* @return Change | |
*/ | |
export function removeImport( | |
source: SourceFile, | |
fileToEdit: string, | |
symbolName: string, | |
fileName: string, | |
) { | |
const rootNode = source; | |
const allImports = findNodes(rootNode, SyntaxKind.ImportDeclaration); | |
const relevantImports = allImports.filter((node) => | |
node | |
.getChildren() | |
.filter(isStringLiteral) | |
.map((n) => n.text) | |
.includes(fileName), | |
); | |
const importSpecifierNode = relevantImports | |
.flatMap((n) => findNodes(n, SyntaxKind.ImportSpecifier)) | |
.map((n) => n as ImportSpecifier) | |
.find((n) => | |
findNodes(n, SyntaxKind.Identifier) | |
.map((i) => i.getText()) | |
.includes(symbolName), | |
); | |
if (!importSpecifierNode) { | |
return new NoopChange(); | |
} | |
const deleteNode = | |
importSpecifierNode.parent.elements.length === 1 | |
? importSpecifierNode.parent.parent.parent | |
: importSpecifierNode; | |
return new RemoveChange( | |
fileToEdit, | |
deleteNode.getStart(), | |
deleteNode.getText(), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment