Is there a way to remove unused imports and declarations from Angular 2+?

ske picture ske · Oct 13, 2017 · Viewed 95k times · Source

I'm assigned to take some messed code from other developers who have already left the company recently.

I am curiously asking is there some plug-in of Visual Studio Code or other means that could help us to tidy and organize the imports and references quickly and effectively?

For example, there are maybe hundreds of imports like this

import { AutoCompleteModule,InputSwitchModule } from 'primeng/primeng';
import { ListboxModule } from 'primeng/primeng';

could be converted to similarily

import { AutoCompleteModule,
         InputSwitchModule,
         ListboxModule  } from 'primeng/primeng';

Or other functions like automatically removing those unused imports and declarations from the app.module or from all components through the whole project?

Thanks for any feedback!

Answer

Muhammad Rehan Qadri picture Muhammad Rehan Qadri · Oct 13, 2017

Edit (as suggested in comments and other people), Visual Studio Code has evolved and provides this functionality in-built as the command "Organize imports", with the following default keyboard shortcuts:

option+Shift+O for Mac

Alt + Shift + O for Windows


Original answer:

I hope this visual studio code extension will suffice your need: https://marketplace.visualstudio.com/items?itemName=rbbit.typescript-hero

It provides following features:

  • Add imports of your project or libraries to your current file
  • Add an import for the current name under the cursor
  • Add all missing imports of a file with one command
  • Intellisense that suggests symbols and automatically adds the needed imports "Light bulb feature" that fixes code you wrote
  • Sort and organize your imports (sort and remove unused)
  • Code outline view of your open TS / TSX document
  • All the cool stuff for JavaScript as well! (experimental stage though, better description below.)

For Mac: control+option+o

For Win: Ctrl+Alt+o