@mathonsunday/dead-code-toolkit
v0.2.1
Published
Comprehensive dead code detection and cleanup toolkit for TypeScript projects. Detects unused exports, files, dependencies, type errors, and more via Knip, TypeScript, ESLint, and custom analysis.
Maintainers
Readme
@mathonsunday/dead-code-toolkit
Comprehensive dead code detection and cleanup toolkit for TypeScript projects
Detects unused exports, files, dependencies, type errors, and more via Knip, TypeScript, ESLint, and custom analysis. Perfect for keeping TypeScript codebases clean and maintaining high code quality.
Features
✨ Multi-layered Detection
- Knip: Unused exports, files, dependencies (symbol-level)
- TypeScript: Type errors and unused variables
- ESLint: Linting issues and redundant types
- Union Exhaustiveness: Validates discriminated unions
🔧 Automated Setup
- One-command project setup:
npx @mathonsunday/dead-code-toolkit setup - Detects project type and generates optimal configurations
- Optional pre-commit hooks via
--hooksflag
🚀 LLM-Friendly
- Callable as an MCP tool for AI assistance
- Structured JSON output for easy interpretation
- Action items and recommendations
- Perfect for Claude, ChatGPT, and other LLMs
📊 Reporting
- Human-readable terminal output
- JSON format for programmatic use
- LLM-friendly summaries
- Detailed suggestions for fixes
Installation
npm install --save-dev @mathonsunday/dead-code-toolkitQuick Start
CLI Usage
Analyze your project for dead code:
npx dead-code-toolkit analyzeOutput as JSON (for LLMs):
npx dead-code-toolkit analyze --jsonGet brief summary:
npx dead-code-toolkit analyze --summarySpecific checks:
npx dead-code-toolkit analyze --checks knip,typescriptRun individual checks:
npx dead-code-toolkit check:knip
npx dead-code-toolkit check:typesProgrammatic Usage
import { analyzeDeadCode, createJSONReport } from '@mathonsunday/dead-code-toolkit';
const result = await analyzeDeadCode({
projectRoot: process.cwd(),
checks: ['knip', 'typescript'],
verbose: true,
});
console.log(`Found ${result.summary.totalIssues} issues`);
console.log(`${result.summary.fixableCount} can be auto-fixed`);
// Get JSON report for LLM consumption
const report = createJSONReport(result);
console.log(JSON.stringify(report, null, 2));Setup in New Project
Automatic setup:
npx @mathonsunday/dead-code-toolkit setupThis auto-detects your project type and generates optimal configurations. Use --hooks flag to also install pre-commit hooks (optional).
Configuration
The toolkit auto-detects your project structure and generates appropriate configs. You can override defaults:
knip.json - Symbol-level dead code detection
{
"entry": ["src/main.ts", "api/handler.ts"],
"project": ["src/**/*.ts", "api/**/*.ts"],
"ignore": ["dist/**", "node_modules/**"]
}ESLint rules - Add to eslint.config.js:
export default [
{
rules: {
'@typescript-eslint/no-unused-vars': 'warn',
'@typescript-eslint/no-redundant-type-constituents': 'warn',
'@typescript-eslint/switch-exhaustiveness-check': 'error',
},
},
];package.json scripts:
{
"scripts": {
"dead-code": "knip",
"dead-code:fix": "knip --fix",
"dead-code:analyze": "dead-code-toolkit analyze",
"verify": "npm run type-check && npm run lint && npm run dead-code"
}
}LLM Integration
Use with Claude or other LLMs as an MCP tool:
// In your tool registry
const deadCodeTool = {
name: 'dead_code_analysis',
description: 'Analyze TypeScript project for dead code',
execute: async (input) => {
const result = await analyzeDeadCode({
projectRoot: input.projectRoot,
checks: input.checks || ['knip', 'typescript'],
});
return createJSONReport(result);
},
};LLM Workflow:
- User: "Help clean up dead code"
- LLM: Calls
dead_code_analysistool - Tool: Returns structured findings
- LLM: Interprets results and guides user
- User: Approves fixes
- LLM: Applies changes
Architecture
Checker Layers
| Layer | Detection Method | Scope | |-------|-----------------|-------| | Knip | Symbol analysis | Exports, files, dependencies | | TypeScript | Type compiler | Type errors, unused variables | | ESLint | Linting rules | Unused variables, redundant types, union exhaustiveness |
Finding Categories
unused-export- Exported but never usedunused-file- File never importedunused-dependency- Package in package.json but unusedtype-error- TypeScript compilation errorunused-var- Variable declared but never usedunused-param- Function parameter never usedredundant-type- Union with overlapping membersunion-issue- Discriminated union not exhaustively handled
Known Limitations
- Semantic dead code - Cannot detect if code serves no business purpose
- Dynamic imports - May miss
import(./${variant}) - Reflection - Runtime string-based access not tracked
- Cross-project usage - Only analyzes within single project
- Performance - May be slow on 100k+ LOC projects (optimization in progress)
Troubleshooting
"Knip not installed"
npm install --save-dev knip"TypeScript not found"
npm install --save-dev typescript"No issues found but I think there's dead code"
- Run with
--verboseflag for detailed output - Check
knip.jsonentry points are correct - Verify project structure matches config
License
MIT
