You can cleanup this by using TypeScript, ESLint, or Angular CLI’s custom schematics for automation.
Option 1: Use ESLint for Cleanup (Recommended)
This is the best practical way to clean unused imports:
1. Install ESLint (if not already installed):
ng add @angular-eslint/schematics
2. Add the rule to remove unused imports:
In your .eslintrc.json
:
"rules": {
"@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }],
"no-unused-imports": "warn"
}
If no-unused-imports
is not available, install this plugin:
npm install eslint-plugin-unused-imports --save-dev
Then update .eslintrc.json
:
"plugins": ["unused-imports"],
"rules": {
"unused-imports/no-unused-imports": "warn",
"unused-imports/no-unused-vars": [
"warn",
{ "vars": "all", "varsIgnorePattern": "^_", "args": "after-used", "argsIgnorePattern": "^_" }
]
}
Then run:
npx eslint . --fix
Option 2: Create a Custom Schematic
If you really want to create your own schematic (e.g. cleanup-unused-imports
), here's how:
1. Create a custom schematic workspace:
npm install -g @angular-devkit/schematics-cli
schematics blank --name=cleanup-unused-imports
cd cleanup-unused-imports
2. Update src/cleanup-unused-imports/index.ts
to do cleanup
Writing AST-based code to remove unused imports is complex — better handled by ESLint or ts-morph
.
If you're sure, you'd use ts-morph
to parse files and remove unused imports.
3. Test your schematic
npm link
ng g cleanup-unused-imports
Summary
Goal | Best Tool |
Remove unused imports | ESLint with --fix |
Create Angular schematic | Use @angular-devkit/schematics-cli |
Clean with AST | Use ts-morph (advanced) |