Last active
December 22, 2023 00:03
-
-
Save dsherret/0bae87310ce24866ae22425af80a9864 to your computer and use it in GitHub Desktop.
Searches files for any exported declarations that aren't used in other files.
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
// this could be improved... (ex. ignore interfaces/type aliases that describe a parameter type in the same file) | |
import { Project, TypeGuards, Node } from "ts-morph"; | |
const project = new Project({ tsConfigFilePath: "tsconfig.json" }); | |
for (const file of project.getSourceFiles()) { | |
file.forEachChild(child => { | |
if (TypeGuards.isVariableStatement(child)) { | |
if (isExported(child)) | |
child.getDeclarations().forEach(checkNode); | |
} | |
else if (isExported(child)) | |
checkNode(child); | |
}); | |
} | |
function isExported(node: Node) { | |
return TypeGuards.isExportableNode(node) && node.isExported(); | |
} | |
function checkNode(node: Node) { | |
if (!TypeGuards.isReferenceFindableNode(node)) | |
return; | |
const file = node.getSourceFile(); | |
if (node.findReferencesAsNodes().filter(n => n.getSourceFile() !== file).length === 0) | |
console.log(`[${file.getFilePath()}:${node.getStartLineNumber()}: ${TypeGuards.hasName(node) ? node.getName() : node.getText()}`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've taken this idea a little bit further and built ts-prune: https://github.com/nadeesha/ts-prune
Thanks for the inspiration!