Skip to content

Instantly share code, notes, and snippets.

@manbearwiz
Created September 1, 2022 20:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manbearwiz/5ec10b964c3fa262594a6f7ce685bfea to your computer and use it in GitHub Desktop.
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.
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