Skip to content

Instantly share code, notes, and snippets.

@haskellcamargo
Last active February 17, 2024 09:54
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 haskellcamargo/f16b66c0d1e64638402d9618c9b4b035 to your computer and use it in GitHub Desktop.
Save haskellcamargo/f16b66c0d1e64638402d9618c9b4b035 to your computer and use it in GitHub Desktop.
import type { NodePath } from '@babel/traverse';
/**
* Finds dependencies of a declaration and removes the ones that are used exclusively
* by this declaration.
*
* NOTE: this only works for runtime bindings. Type bindings are excluded as I'd need to patch
* Babel to keep track of type bindings in the context of a declaration, and ain't nobody got
* time for that for now.
*
* @experimental
*/
export function removeDeclarationDeps(path: NodePath) {
for (const binding of Object.values(path.scope.bindings)) {
const pathsBelongingToDeclaration = binding.referencePaths.filter((referencePath) =>
referencePath.findParent((parentPath) => parentPath === path),
);
if (binding.referencePaths.length === pathsBelongingToDeclaration.length) {
binding.path.remove();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment