DEV Community

Krzysztof Platis
Krzysztof Platis

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

Oldest comments (1)

Collapse
 
alexsoyes profile image
Alex so yes

I just created an account to thank you bro 🔥