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

6

358

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 throughout the project?

Thanks for any feedback!

Olympic answered 13/10, 2017 at 4:47 Comment(4)
I too am wondering if extraneous imports into components specifically are a drag on performance.Immotile
https://mcmap.net/q/92650/-is-there-a-way-to-remove-unused-imports-and-declarations-from-angular-2-closed vscode 1.22 Shift+Alt+O - works for me!Resonate
Can be done from the command line (or git hook) too: npmjs.com/package/organize-imports-cliIdonna
I had this question too before creating an extension for that (marketplace.visualstudio.com/…) and discovering just after publishing it, that it can be done via Code Actions (Ctrl/Cmd + .) over an unused import to remove it or all the unused imports without sorting them.Uglify
S
608

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

Sadirah answered 13/10, 2017 at 4:58 Comment(12)
Thanks for turning me onto this add-on, it rocks! Up until I just installed it I used to have Auto-Import extension installed to take care of that little piece of functionality (auto importing). But after installing TypeScript Hero... wow, it does everything I need it to do, including sorting dependencies in alphabetical order within the import statements themselves, getting rid of imports that are not used within the component classes, etc!Immotile
In 2018 TS Hero's project maintainer has said he would discontinue the extension, since it has become obsolete after the implementation of the main functionalities directly in VS Code (see other coments).Oneiric
Any way to call Alt+Shift+O without reordering the imports?Reeducate
Alt + Shift + O for Linux tooBurchfield
it just displays a popup, where is the automatically part in this answer ?Timms
Currently, one of the benefits of TypeScript Hero over VS Code's organizer is being able to separate/group imports (e.g. global and local imports separated by new line). If you want to organize imports on save with this plugin, you can add the following in settings.json "typescriptHero.imports.organizeOnSave": trueLynch
Not sure why, but for me, it was command shift o. Using mac and vs code version 1.58.0Revers
+1 to @XCS. Any way possible to use "organize imports" command only for removing unused imports and declarations and not reordering the imports?Walters
How can I run this for all the typescript/angular files ?Rolfrolfe
This has recently stopped working for me!Amphibole
works only for javascript/typescript, not for C#Midtown
Option + shift + O , does indeed remove unused imports. Is there a way to remove unused variables too?Aikens
L
235

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!

Lubricious answered 12/2, 2019 at 23:28 Comment(7)
This seems to conflict with ESLint Prettier plugin. It is trying to make an one-line import but ESLint is trying to break in multiple lines.Falmouth
Same problem as @Richard. Seems to be an open issue - github.com/prettier/prettier-vscode/issues/716Gambado
Is there a way to disable the removal of unused imports while keeping imports sorted?Phlox
In my experience doing auto organise imports and formats shouldn't be done on save as it can cause git conflict nightmares. It should be up to the developer to do it before saving the file if they wish. If they are working on new files it's ok but not when you are just applying hot fixes to existing code. Sure, it's easier to use something like Husky or Github actions on the post-commit stage to lint files but legacy projects normally won't have this and you only want to see change diffs and not formatting diffs.Benzoyl
Can I set this for the whole team?Rally
Is there something similar for unused variables ?Jerol
2024 UPDATE: As per VS Code, "source.organizeImports": true changed to "source.organizeImports": "explicit" and instead of false now it's never. check the link for more details.Madden
M
194

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.

Millian answered 6/4, 2018 at 16:22 Comment(3)
Nice! I've been using ctrl+shift+- since forever and now I can find and change the shortcut.Haemocyte
I had to install it, didn't come in my install of 1.37.1Glorification
does not work for C#Midtown
L
65

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.

Liter answered 22/3, 2018 at 11:51 Comment(0)
F
62

Since VSCode v.1.24 and TypeScript v.2.9 Organize Imports was added:

For Mac: option+Shift+O

For Win: Alt+Shift+O

Fluster answered 8/6, 2018 at 8:48 Comment(3)
more important to some, the command is Organize Imports or editor.action.organizeImportsRachitis
@Rachitis Is there a way to disable the removal of unused imports while keeping imports sorted?Phlox
That keybinding doesn't work for me, instead, I run Shift + CMD + P and searched for Organize Imports and It worksSudoriferous
L
26

There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.

In the article the author explains it like this:

Make a stand alone tslint-imports.json file that has the following in it:

{
  "extends": ["tslint-etc"],
  "rules": {
    "no-unused-declaration": true
  }
}

Then run the following command to fix the imports:

 tslint --config tslint-imports.json --fix --project .

Consider fixing any other errors it throws. (I did)

Then check the project works by building it:

ng build

or

ng build name_of_project --configuration=production 

End: If it builds correctly, you have successfully removed imports automatically!

NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.

Lavine answered 8/8, 2019 at 20:33 Comment(4)
I get Could not find implementations for the following rules specified in the configuration: no-unused-declaration , so I guess this solution doesn't work anymore.Landahl
I am using tslint version 5.20.1Landahl
This helped me; thanks. The one thing that I added for my project (React) was an ignore option to "no-unused-declaration". See this tslint-imports.json for an ignore example.Palaestra
There is an extension just for that (marketplace.visualstudio.com/…). I created it because the native “Organize imports” provided by VS Code also changes the order of the imports, that’s annoying for me.Uglify

© 2022 - 2024 — McMap. All rights reserved.