DEV Community

Krzysztof Platis
Krzysztof Platis

Posted on • Updated on

Auto-add missing imports on file save in VS Code ✨

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):

Image description

Then add the following settings to your opened User settings.json:

  "editor.codeActionsOnSave": {
    "source.organizeImports": true,
    "source.addMissingImports": true
  },
Enter fullscreen mode Exit fullscreen mode

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):

Image description

And add the following setting to your opened keybindings.json:

  {
    "key": "ctrl+s",
    "command": "editor.action.sourceAction",
    "args": {
      "kind": "source.addMissingImports",
      "apply": "first"
    }
  }
Enter fullscreen mode Exit fullscreen mode

and then press [CTRL + S]

Save the file!

Before 🙄

Image description

After 🤩

Image description

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. 😉

If you really feel like buying me a coffee

... then feel free to do it. Many thanks! 🙌

Buy Me A Coffee

Top comments (4)

Collapse
 
alexsoyes profile image
Alex so yes

I just created an account to thank you bro 🔥

Collapse
 
tariky profile image
Tarik Čaplja

Syntax in VS Code is changed little bit here is updated version:

"editor.codeActionsOnSave": {
    "source.organizeImports": "always",
    "source.addMissingImports": "always"
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mirkobozzetto profile image
Mirko Bozzetto

Killer feature, I don't know why vscode don't give it by default x)

BIG UP to U

Collapse
 
truemoein profile image
Moein Alizadeh

Nice!