Remove Dead Code with Knip (Streamline Before Upgrades)
• Tooling
Why Dead Code Hurts
Leftover code confuses AI assistants and teammates, increases maintenance surface, hides bugs, and inflates context windows. Before big upgrades, decluttering avoids fixing things that should just be removed.
What Knip Does
Knip statically analyzes your project to find unused files, exports, and dependencies. It understands many frameworks and build tools, and produces actionable reports you can iterate on until you reach an acceptable level of cleanliness.
Quick Start
# Add temporarily (or install locally)
npx knip
# Or install as a dev dependency
npm i -D knip
npx knip
# CI-friendly (non-interactive) output
npx knip --ci
# Machine-readable report (review in your editor)
npx knip --json > knip-report.json
Start by running Knip without changing anything. Review the report and remove obvious dead code first (unused files/exports and known-dead packages).
Iterate Until Clean
Dead code can be layered. An unused function might call another function that appears used—until you remove the first one. Run Knip multiple times during cleanup:
# Pass 1: identify and remove the obvious
npx knip
# Remove dead files/exports/packages
# ... commit small safe changes ...
# Pass 2+: re-run until results plateau
npx knip
Small, frequent passes keep risk low and make reviews easy. Stop when the remaining findings are intentional (e.g., dynamic imports, codegen stubs) or out of scope.
Package Scripts and Baseline
Add convenience scripts so the whole team runs it the same way:
{
"scripts": {
"knip": "knip",
"knip:ci": "knip --ci",
"knip:json": "knip --json > knip-report.json"
},
"devDependencies": {
"knip": "^5"
}
}
You can also create a knip.json to ignore known false positives or mark files as entry points. See the docs for patterns and framework presets.
When to Run Knip
- Before upgrades: shrink the codebase so you only migrate what matters.
- Before enabling AI tools: reduce noise so suggestions focus on real code.
- On a schedule: add a periodic job or a manual checklist item each release.
Caveats
- Dynamic usage (reflection, string-based imports) may require explicit include or ignore entries.
- Generated code and plugin systems can look unused—baseline or exclude where appropriate.
- Prefer small PRs; remove code in steps rather than giant diffs.
Summary
Knip is an effective decluttering tool: run it, remove safe dead code, and repeat until clean. You’ll reduce cognitive load, shrink context for AI and humans, and avoid wasting time upgrading code you don’t need.