Do you spend precious time manually organizing imports and fixing missing ones while coding in VS Code? There's a faster and more efficient way. By enabling a simple but powerful feature in the settings, you can automate these tasks upon file save and significantly boost your coding productivity. Let's explore how this feature works and how you can start using it today.
Auto-add missing imports on file save
Using the Command Palette (CMD + SHIFT + P
), open the option Preferences: Open User Settings (JSON)
:
Then add the following settings to your opened User settings.json
:
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.addMissingImports": true
},
Note: When there is more than one possible suggested import path for a token, such a missing import won’t be auto-added.
Keyboard Shortcut to add missing imports
However, you can configure a keyboard shortcut to auto-add missing imports (and it can handle a situation when many import paths are suggested; e.g. choose the first one by default).
Using the Command Palette (CMD + SHIFT + P
), open the option Preferences: Open Keyboard Shortcuts (JSON)
:
And add the following setting to your opened keybindings.json
:
{
"key": "ctrl+s",
"command": "editor.action.sourceAction",
"args": {
"kind": "source.addMissingImports",
"apply": "first"
}
}
and then press [CTRL + S]
Save the file!
Before 🙄
After 🤩
Disclaimer
Please expect that sometimes VS Code might suggest using a not your preferred path (e.g. not from the proper relative file or from a proper sub entry point @package/xxx/yyy
, but from an index.ts barrel or from absolute directory - which depending on your setup might cause compilation errors later on). So please be vigilant with VS Code resolving import paths for you. 😉
Top comments (5)
Syntax in VS Code is changed little bit here is updated version:
I just created an account to thank you bro 🔥
Killer feature, I don't know why vscode don't give it by default x)
BIG UP to U
Nice!