Jon Sud
Jon Sud

Reputation: 11641

How to remove unused imports with a command?

I have files in my nx project with import declaration without any use and I want to remove them.

After I searched in stackoverflow I found the answer to open the file in vscode, and press alt+shift+o and when the declaration is not used then it's remove and sort the import.

But I have 10,000 files. so is there a command to do that in all those files? I looking in eslint but there is no rule for that.

Upvotes: 11

Views: 10984

Answers (2)

Junius L
Junius L

Reputation: 16132

Install the no-unused-imports plugin

Add unused-imports to the plugins section of your .eslintrc file

{
  "plugins": ["...", "unused-imports"]
}

add the following rules

"no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": [
  "warn",
  { "vars": "all", "varsIgnorePattern": "^_", "args": "after-used", "argsIgnorePattern": "^_" }
    ],

Then add script to your package.json file

"scripts": {
   ...
   "fix-lint-errors": "eslint nx --fix"
},

from command line run the script

npm run fix-lint-errors

or

yarn fix-lint-errors

Upvotes: 9

NabaaJafar
NabaaJafar

Reputation: 13

If you are a heavy user, so you can simply open your preference settings then add the following to your settings.json:

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

Or you can make a stand alone file that has the following in it:

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

Then run the following command to fix the imports:

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

Then use

ng build

or

ng build name_of_project --configuration=production 

Upvotes: 1

Related Questions