david_adler
david_adler

Reputation: 10942

How do I delete all unused imports in the active file with one command in VS Code (typescript)?

Previously, I used to be able to do CMD+SHIFT+p > Organize imports and this would both sort and delete unused imports. This functionality seems to have broken.

How can I delete unused imports quickly with one command?

Current workaround is: click on unused import, CMD+. > Delete unused imports.

enter image description here

Languages for which this is applicable (typescript, typescriptreact, javascript, javascriptreact).

I have confirmed VS code is using a recent version of typescript unlike people in this post enter image description here

Upvotes: 4

Views: 16501

Answers (3)

Mike S
Mike S

Reputation: 3169

It looks like this is now built in. First, you'll see that unused imports are greyed out. There's a lightbulb for code actions, and that includes a menu for deleting all unused imports.

enter image description here

Upvotes: 0

Mark
Mark

Reputation: 181399

In v1.73 there should be a command (it is in Insiders already) to remove all unused imports, see Merged PR: Add removeUnusedImports command:

{
  "key": "",
  "command": "javascript.removeUnusedImports"
},

{
  "key": "",
  "command": "typescript.removeUnusedImports"
}

These are unbound by default and although they are in the Keyboard Shortcuts editor they don't appear in the Command Pallette for some reason.


Previous answer which may still help some:

There does not appear to be a built-in way to access the delete all imports functionality. But you can install the Remove Unused Imports extension

VS Code extension to remove unused ES6 imports inside JavaScript and TypeScript files (.js, .jsx, .ts and .tsx extensions) without changing the current order, as opposed to the built-in VS Code "Organize Imports" functionality.

and

try this keybinding:

{
  "key": "cmd+shift+r",            // or whatever you want
  "command": "remove-unused-imports.main",
}

Upvotes: 2

david_adler
david_adler

Reputation: 10942

It turns out that Organize Imports does actually work as expected but it was conflicting with the Deno plugin.

I found this out by using the amazingly useful Extension Bisect feature which is built into Visual Studio Code. Extension Bisect disables half your extensions and asks you to check if the issue persists. This process is repeated until only a single extension is left. I strongly recommend trying it out via CMD+SHIFT+P > Start Extension Bisect

Turns out my issue is a duplicate of this GitHub issue.

Upvotes: 4

Related Questions