» npm install eslint-plugin-unused-imports
» npm install eslint-plugin-unused-vars-and-imports
Using unused-imports plugin and unused-imports/no-unused-imports-ts rule, eslint --fix will remove the imports.
Here is an example repo which --fix removes the unused imports.
https://github.com/moshfeu/eslint-ts-unused-imports
Setup
yarn add -D eslint-plugin-unused-imports
// eslint.config.js
import tseslint from "typescript-eslint";
import unusedImports from "eslint-plugin-unused-imports";
export default tseslint.config(
{
plugins: {
"unused-imports": unusedImports,
},
rules: {
"unused-imports/no-unused-imports": "warn",
},
}
);
Old answer
eslint has a built-in fix option.
eslint ... --fix
If rules contains no-unused-vars, eslint will "fix" the unused import by removing them (along with other auto fixes).
You can also use shortcuts in VSCode, if it needs to be done quickly and without extra effort:
- Option + Shift + O for Mac
- Alt + Shift + O for Windows
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
If you are a heavy vscode 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 tslint 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