Last updated: Apr 6, 2024
Reading time·4 min
You can use a keyboard shortcut to remove the unused imports in VS Code:
Shift
+ Alt
+ O
(the letter O
, not zero).Shift
+ Option
+ O
(the letter O
, not zero).Here is a short clip that demonstrates how this works.
The keyboard shortcut runs the Organize Imports command.
The command:
The command works for both JavaScript and TypeScript files.
VS Code also has a Remove Unused Imports command if you only need to remove the unused imports without sorting.
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.At the time of writing the command is available for JavaScript and TypeScript.
By default, the command is not bound to a specific key combination.
You can configure one by using the keyboard shortcuts menu.
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.You can also select a row and click on the Pencil icon to set a keyboard shortcut.
Enter
to confirm.You can also trigger the command via the Command Palette.
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.You can also view the keyboard shortcut for your operating system when using the Command Palette.
Here is a short clip of how this works.
The command doesn't only remove the unused imports, it also sorts the import statements in the file.
If you need to change the default keyboard shortcut of the Organize Imports command:
Ctrl
+ Shift
+ P
on Windows and Linux.Command
+ Shift
+ P
on macOS.F1
to open the Command Palette.Enter
to confirm.You can also select the row and click on the pencil icon to set a keyboard shortcut for the command.
If you need to automatically remove the unused imports on save:
Ctrl
+ Shift
+ P
(or Command
+ Shift
+ P
on macOS).F1
to open the Command Palette.Type user settings json.
Click on Preferences: Open User Settings (JSON)
"editor.formatOnSave": true, // Sort imports and automatically remove // unused imports when pressing CTRL + S "editor.codeActionsOnSave": { "source.organizeImports": true },
Make sure to remove the trailing comma if the property comes last.
If the editor.codeActionsOnSave
object already exists in your settings.json
file, you have to add the source.organizeImports
property to the existing
object.
When the source.organizeImports
property is set to true
, every time you
press Ctrl
+ S
(or Cmd
+ S
on macOS):
Here is a short clip that demonstrates how this works.
You can also set the source.fixAll
property to true
if you want to fix small
syntactical errors automatically on save.
"editor.formatOnSave": true, "editor.codeActionsOnSave": { "source.organizeImports": true, "source.fixAll": true },
Make sure to remove the trailing comma if the property comes last.
I've also written an article on how to remove trailing spaces automatically in VS Code.
You can learn more about the related topics by checking out the following tutorials: