Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I get rid of unused imports VS code?

How do we make sure that all unneeded and unused JavaScript and library imports are cleaned up? Visual Code has a handy keyboard shortcut Alt + Shift + O that you can use to automatically clean up a file.

Why should we remove unused imports?

An unused import still creates a dependency. If you don't realize that a dependency is only because of unused imports, you can waste time updating the module version, investigating vulnerability reports related to that module, etc.

How do I delete all unnecessary Usings in Visual Studio?

Go to Tools > Options > Text Editor > C# > Code Style > Formatting. It has an experimental Format Document Settings where you can have Visual Studio clean up your code. Two of the options are to "Remove unnecessary usings" and "Sort usings". Check these two and you're good to go!


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


As of Visual Studio Code Release 1.22 this comes free without the need of an extension.

Shift+Alt+O will take care of you.


If you're a heavy visual studio user, you can simply open your preference settings and add the following to your settings.json:

...
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
  "source.organizeImports": true
}
....

Hopefully this can be helpful!


To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.