Remove Unused
See original GitHub issueSimilar to methods organizeImports()
, formatText()
, fixMissingImports()
I would like to have a method removeUnused()
that removes any variable, parameter, named import, type parameter, method, etc. that is not used.
/**
* Removes used declarations like variables, parameters, members, etc. from this node descendants.
*
* @param formatSettings - Format code settings.
* @param userPreferences - User preferences for refactoring.
*/
removeUnused(formatSettings: FormatCodeSettings = {}, userPreferences: UserPreferences = {}) {}
Alternatives The method could accept some options to control which kind of nodes should be removed or not. Also if we decide to put the method in SourceFile instead of Node, it could accept a targetnode option:
type RemoveUnusedExclude = 'variable'|'parameter'|'typeParameter'|'import'|'function'|'class'|'type'|'method'|'property'|'constructor'|'etc'
interface RemoveUnusedOptions{
exclude?: RemoveUnusedExclude[]
targetNode?: Node
}
removeUnused(options?: RemoveUnusedOptions):void
Doubts
-
Similarly to formatText() this applies to any node, this method could be declared in
Node
although users will usually call it inSourceFile
. So I’m not sure where would be the best location… -
Should we use TS built in code fixes that already implements this? or should we implement it from scratch so Nodes are not forgotten ?
In some cases it could be tricky to define if something is used or not, like type parameters, exports, etc, and the implementation must be 100% safe, but I could try implementing something like that and see…
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (5 by maintainers)
Or actually maybe just
removeUnusedDeclarations
.After thinking this through, I think what you did in #595 is sufficient. This is normally a refactor that people do at the end and so keeping track of the nodes is not very necessary.
By the way, here’s an example of calling this until there’s no more changes: