
Knip
- 56 installs
- 2 repo stars
- Updated August 3, 2026
- fandhe-ai/agent-reference-skills
Helps with ai & agent building tasks.
About
knip is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- knip
- AI & Agent Building
- AI-coding skill
Knip by the numbers
- 56 all-time installs (skills.sh)
- Ranked #6,750 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/fandhe-ai/agent-reference-skills --skill knipAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 56 |
|---|---|
| repo stars | ★ 2 |
| Last updated | August 3, 2026 |
| Repository | fandhe-ai/agent-reference-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Knip リファレンス
Knip の公式ドキュメント全コアページを網羅したスキル。 ユーザーのタスクに応じて適切な README.md を読み、そこから個別ファイルへ辿ること。
ディレクトリ構成
skills/knip/
SKILL.md
references/
overview/
README.md
configuration.md
features.md
getting-started.md
screenshots-videos.md
explanations/
README.md
comparison-and-migration.md
entry-files.md
plugins.md
why-use-knip.md
features/
README.md
auto-fix.md
catalogs.md
compilers.md
custom-elements.md
integrated-monorepos.md
monorepos-and-workspaces.md
production-mode.md
reporters.md
rules-and-filters.md
script-parser.md
source-mapping.md
guides/
README.md
configuring-project-files.md
contributing.md
handling-issues.md
issue-reproduction.md
namespace-imports.md
performance.md
troubleshooting.md
using-knip-in-ci.md
working-with-commonjs.md
reference/
README.md
cli.md
configuration.md
configuration-hints.md
dynamic-configuration.md
faq.md
integrations.md
issue-types.md
jsdoc-tsdoc-tags.md
known-issues.md
plugins.md
related-tooling.md
typescript/
README.md
unused-dependencies.md
unused-exports.md
writing-a-plugin/
README.md
argument-parsing.md
inputs.md
writing-a-plugin.md
samples/
README.md
auto-fix.md
basic-configuration.md
ci-integration.md
getting-started.md
ignore-patterns.md
jsdoc-tags.md
monorepo-workspaces.md
output-formats.md
production-mode.md
rules-and-filters.md
scripts/
README.md
ci.md
cli.md
debug.md
fix.md
install.md
lint.md探索手順
タスクからカテゴリを引き、カテゴリの README.md で目的のページを特定する:
1. 下記マッピング表でタスクに対応するカテゴリを探す 2. そのカテゴリの references/{category}/README.md を参照して目的のページを特定する 3. 該当ページの .md を Read して詳細を確認する
タスク → カテゴリ マッピング
| タスク | カテゴリ | 参照 README |
|---|---|---|
| インストール・初期設定・基本的な使い方を知りたい | overview | references/overview/README.md |
| 機能一覧・ゼロ設定の仕組みを知りたい | overview | references/overview/README.md |
| エントリーファイル・プラグインの仕組みを理解したい | explanations | references/explanations/README.md |
| 導入理由・他ツールとの比較・移行手順を知りたい | explanations | references/explanations/README.md |
| auto-fix・production mode・monorepo・reporters を使いたい | features | references/features/README.md |
| rules / filters・compilers・script parser を設定したい | features | references/features/README.md |
| プロジェクトファイル設定・トラブルシューティング・CI 統合 | guides | references/guides/README.md |
| パフォーマンス最適化・CommonJS 対応・namespace imports | guides | references/guides/README.md |
| CLI フラグ・設定オプション・issue types・JSDoc タグ | reference | references/reference/README.md |
| FAQ・プラグイン一覧・統合ツール・既知の問題を調べたい | reference | references/reference/README.md |
| 未使用 exports / dependencies の検出詳細を理解したい | typescript | references/typescript/README.md |
| カスタムプラグインを作成したい | writing-a-plugin | references/writing-a-plugin/README.md |
| 典型的な使い方・実例を確認したい | samples | samples/README.md |
| インストール・CLI コマンド・CI 実行コマンドを知りたい | scripts | scripts/README.md |
Comparison & Migration
Source: https://knip.dev/explanations/comparison-and-migration
Migration Strategy
Delete the previous tool's dependency and configuration file, then get started with Knip.
Comparison
depcheck (Archived → recommends Knip)
Analyzes dependencies to find unused and missing packages. Offers plugins and compiler support.
Equivalent: knip --dependencies
unimported (Archived → recommends Knip)
Fast tool for finding unused dependencies. Operates in production mode only.
Equivalent: knip --production --dependencies --files
ts-prune (Archived → recommends Knip)
Finds unused exports in TypeScript projects. Zero configuration.
Equivalent: knip --include exports,types,nsExports,nsTypes
ts-unused-exports
Focuses on unused exported symbols in TypeScript projects. Similar to ts-prune.
tsr (Archived → recommends Knip)
Removes unused code from TypeScript projects. Works with single tsconfig.json.
Related Projects
deadfile, DepClean, dependency-check, find-unused-exports, next-unused, npm-check, renoma
Entry Files
Source: https://knip.dev/explanations/entry-files
Overview
Entry files are starting points for Knip to determine which files are used. More entry files lead to increased codebase coverage and more dependency discovery.
Default Entry File Patterns
{
"entry": [
"{index,cli,main}.{js,cjs,mjs,jsx,ts,cts,mts,tsx}",
"src/{index,cli,main}.{js,cjs,mjs,jsx,ts,cts,mts,tsx}"
],
"project": ["**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx}!"]
}Custom configuration values override defaults (not merge).
Plugins
Plugins automatically contribute additional entry files. Enabling Remix, Storybook, Vitest plugins adds their respective entry files.
package.json
Knip examines these fields for entry points:
mainbinexports
Additionally, npm scripts are parsed to identify entry files and dependencies through the script parser.
Gitignore
Files listed in .gitignore are excluded by default. Override with --no-gitignore.
Related
- Configuring project files guide
- Script parser feature
Plugins
Source: https://knip.dev/explanations/plugins
What Does a Plugin Do?
Plugins activate automatically when their associated package appears in package.json dependencies. Each plugin:
- Handles configuration files (e.g.,
astro.config.mjs) - Adds entry file patterns (e.g.,
src/pages/**/*.astro) - Defines command-line arguments
Configuration Files
Knip uses plugins to parse configuration files and extract dependency references not found through static import analysis.
ESLint Example
{
"extends": ["airbnb", "prettier"],
"plugins": ["@typescript-eslint"]
}Identified dependencies: eslint-config-airbnb, eslint-config-prettier, @typescript-eslint/eslint-plugin
Vitest Example
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
coverage: { provider: 'istanbul' },
environment: 'happy-dom',
},
});Revealed dependencies: @vitest/coverage-istanbul, vitest-environment-happy-dom
Entry Files
Plugins automatically configure entry file patterns:
- Next.js:
pages/**/*.{js,jsx,ts,tsx} - Vitest:
**/*.{test,test-d,spec,spec-d}.ts
Override in knip.json:
{
"playwright": {
"entry": "src/**/*.integration.ts"
}
}Entry Files from Config Files
Angular
Reads angular.json to extract main entry file, @angular-devkit/build-angular dependency, and tsconfig.app.json reference.
GitHub Actions
Parses workflow YAML run scripts to identify entry files like scripts/build.js.
Webpack
Extracts entry files from entry config and dependencies from module rules.
Bringing It All Together
A config file is processed both as: 1. An entry file (to resolve static imports) 2. A config file (to parse and extract dynamic dependencies)
Config File Location
Specify non-default locations in knip.json:
{
"playwright": { "config": ["e2e/playwright.config.ts"] },
"vite": "packages/*/vite.config.ts"
}Summary
1. Config files are dynamically loaded and parsed by plugins 2. Entry files are added to the module graph 3. Both can recursively lead to additional entries, configs, and dependencies
explanations
| Name | Description | Path |
|---|---|---|
| Comparison & Migration | Delete the previous tool's dependency and configuration… | comparison-and-migration.md |
| Entry Files | Entry files are starting points for Knip to determine… | entry-files.md |
| Plugins | Plugins activate automatically when their associated… | plugins.md |
| Why use Knip? | Knip identifies and fixes unused dependencies, exports… | why-use-knip.md |
Why use Knip?
Source: https://knip.dev/explanations/why-use-knip
Overview
Knip identifies and fixes unused dependencies, exports, and files. It performs deep analysis from fine-grained entry points based on actual frameworks and tooling in (mono)repos.
Less is More
- Maintenance: Easier when there's less code
- Performance: Unused code impacts startup, build, and bundle size. Tree-shaking is not a complete solution
- Onboarding: New team members benefit from clean codebases
- Regression Prevention: Like TypeScript/ESLint/Prettier, prevents dead code from being reintroduced
- Code Readability: Dead code creates confusion
Related principle: YAGNI (You Aren't Gonna Need It)
Automation
Knip automates finding clutter that would be tedious manually. Use alongside ESLint or Biome — after removing unused variables, Knip may find even more unused code.
Comprehensive Coverage
Plugin-based dependency finding identifies additional entry/config files. Analyzing more files reveals unused exports and dependency usage patterns. This effect multiplies in monorepo environments.
Greenfield or Legacy
- New projects: Maintain cleanliness from inception
- Legacy projects: May require configuration and produce false positives initially
- Recommendation: Use Knip in CI to prevent future regressions
Unobtrusive Design
Knip requires no proprietary syntax. Uses standardized JSDoc annotations like @lintignore instead of // knip-ignore comments.
Auto-fix
Source: https://knip.dev/features/auto-fix
Overview
--fix automatically removes unused code:
- Remove
exportkeyword from unused exports/re-exports/types - Remove
export defaultfrom unused default exports - Remove unused enum and namespace members
- Remove unused
dependencies/devDependenciesfrompackage.json - Remove unused files (with
--allow-remove-files) - Remove unused catalog entries
Important: Use a VCS like Git to review and undo changes.
CLI Flags
knip --fix
knip --fix --allow-remove-files
knip --fix-type exports,types
knip --fix --format--fix-type accepts: dependencies, exports, types, files, catalog
--format auto-formats with Biome, deno fmt, dprint, or Prettier.
Post-Fix Considerations
1. Formatting: Use --format or run a dedicated formatter 2. Unused Variables: Use ESLint/Biome for internal variables (beyond Knip's scope) 3. Dependency Verification: Review package.json changes and update lockfile 4. Unlisted Dependencies: Install missing dependencies identified by Knip
Examples
Exports
// Before
export const unused = 1;
export default class MyClass {}
// After
const unused = 1;
class MyClass {}Re-exports
// Before
export { Cat, Dog } from './pets';
export { Lion, Elephant } from './jungle';
// After
export { Elephant } from './jungle';Enum Members
// Before
export enum Directions { North = 1, East = 2, South = 3, West = 4 }
// After
export enum Directions { North = 1, East = 2 }Dependencies
// Before
{ "dependencies": { "rimraf": "*", "unused-dep": "*" } }
// After
{ "dependencies": { "rimraf": "*" } }CommonJS
// Before
module.exports = { identifier, unused };
// After
module.exports = { identifier };Limitations
Auto-fix does NOT:
- Add unlisted dependencies
- Add unlisted binaries
- Resolve duplicate exports
Catalogs
Source: https://knip.dev/features/catalogs
Overview
Catalogs allow you to define dependency version ranges once and reference them across workspaces in a monorepo. Knip detects unused catalog entries and can remove them automatically.
Supported Catalog Sources
In priority order:
1. pnpm-workspace.yaml (default and named catalogs) 2. .yarnrc.yml 3. package.json 4. package.json#workspaces (Bun)
Detecting Unused Entries
A catalog entry is marked unused when no workspace references it via the catalog: protocol.
{
"dependencies": {
"react": "catalog:",
"zod": "catalog:validation"
}
}Checked fields: dependencies, devDependencies, peerDependencies, optionalDependencies, resolutions, pnpm.overrides.
Filters & Auto-Fix
knip --include catalog
knip --exclude catalog
knip --fix --fix-type catalogThe catalog issue type is included in the --dependencies shortcut filter.
Related
- Auto-fix
- Monorepos & Workspaces
- Issue Types
Compilers
Source: https://knip.dev/features/compilers
Overview
Projects may have non-JS/TS source files requiring compilation. Knip uses compilers to extract import statements from these files.
Built-in Compilers
| Extension | Note |
|---|---|
.astro | Built-in |
.css | Enabled via tailwindcss |
.mdx | Built-in |
.prisma | Built-in |
.sass, .scss | Built-in |
.svelte | Built-in |
.vue | Built-in |
Built-in compilers use regex extraction (fast, no dependencies required).
Manual Enabling
export default {
compilers: {
mdx: true,
},
};Custom Compilers
Function signature:
(source: string, filename: string) => string;Async functions supported. Extensions are automatically added to file patterns.
CSS Example
export default {
compilers: {
css: (text: string) => [...text.matchAll(/(?<=@)import[^;]+/g)].join('\n'),
},
};MDX Example
import { compile } from '@mdx-js/mdx';
export default {
compilers: {
mdx: async text => (await compile(text)).toString(),
},
};Svelte Example
import { compile } from 'svelte/compiler';
export default {
compilers: {
svelte: (source: string) => compile(source, {}).js.code,
},
};Vue Example
Uses vue/compiler-sfc to parse script blocks, script setup blocks, and style blocks.
Custom Elements
Source: https://knip.dev/features/custom-elements
Overview
Knip automatically recognizes custom element class registrations under tag names, preventing false "unused export" reports for web component classes.
Native Registration
The web standard customElements.define() credits the registered class. Supported registration patterns:
- Direct global registry:
customElements.define('my-el', MyEl) - Prefixed access:
window.customElements.define(...),globalThis.customElements.define(...) - Local
CustomElementRegistryinstances - Shadow root scoped registries
- Self-registration via static blocks
Framework Support
Framework-specific decorators and methods are recognized automatically when the framework is listed as a project dependency.
| Framework | Decorator / Method | Import Source |
|---|---|---|
| Lit | @customElement('tag') | lit/decorators |
| FAST | @customElement or .define() | @microsoft/fast-element |
| Stencil | @Component({ tag }) | @stencil/core |
| Catalyst | @controller | @github/catalyst |
Note: Framework decorators are only recognized when imported from the official framework source. Locally-defined or differently-sourced decorators are ignored.
Configuration
No additional configuration is needed. Recognition is automatic when the framework appears in project dependencies.
Related
- Plugins
- Entry Files
Integrated Monorepos
Source: https://knip.dev/features/integrated-monorepos
Overview
Integrated monorepos have multiple projects within a single package.json, with configuration files distributed throughout. Nx integrated style is a notable example.
An integrated monorepo functions as a single workspace.
Entry Files
Default entry points may be insufficient. Use glob patterns:
{
"entry": ["{apps,libs}/**/src/index.{ts,tsx}"],
"project": ["{apps,libs}/**/src/**/*.{ts,tsx}"]
}Plugins
Configure plugins with appropriate globs for distributed config files:
{
"eslint": {
"config": ["{apps,libs}/**/.eslintrc.json"]
},
"cypress": {
"entry": ["apps/**/cypress.config.ts", "apps/**/cypress/e2e/*.spec.ts"]
}
}Internal Workspace Dependencies
Two approaches:
1. List all dependencies in each consuming package.json for fine-grained reporting 2. Use ignoreDependencies: ["@internal/*"] to suppress internal package warnings
Monorepos & Workspaces
Source: https://knip.dev/features/monorepos-and-workspaces
Overview
Knip handles workspaces automatically. Workspaces are directories with a package.json.
Configuration
{
"workspaces": {
".": {
"entry": "scripts/*.js",
"project": "scripts/**/*.js"
},
"packages/*": {
"entry": "{index,cli}.ts",
"project": "**/*.ts"
},
"packages/cli": {
"entry": "bin/cli.js"
}
}
}- Root workspace:
"." - Root-level
entry/projectare ignored in projects with workspaces - Each workspace inherits default values
Workspaces Discovery
Sources (in priority order):
1. workspaces array in package.json (npm, Bun, Yarn, Lerna) 2. packages array in pnpm-workspace.yaml (pnpm) 3. workspaces.packages array in package.json (legacy) 4. workspaces object in Knip configuration
All workspaces must contain a package.json.
Additional Workspaces
Manually add in Knip config:
{
"workspaces": {
"packages/cli": {}
}
}Options per Workspace
ignore,ignoreBinaries,ignoreDependencies,ignoreMembersignoreUnresolved,includeEntryExports- Plugins configurable per workspace
--debugshows workspace details
Filter Workspaces
knip --workspace packages/my-lib
knip -W @myorg/my-libSupports:
- Package names:
@myorg/my-lib - Package globs:
@myorg/* - Directory paths:
packages/my-lib - Directory globs:
./apps/*
Multiple selectors:
knip --workspace @myorg/* --workspace '!@myorg/legacy'
knip --workspace './apps/*' --workspace '@shared/utils'Ancestors and dependents are automatically included.
For isolated workspace linting:
- Combine with strict production mode
- Run Knip from within the workspace directory
Production Mode
Source: https://knip.dev/features/production-mode
Overview
Default mode analyzes all project code including config, test, and Storybook files. Production mode focuses exclusively on shipped code.
Configuration
Append ! to patterns for production-only:
{
"entry": ["src/index.ts!", "build/script.js"],
"project": ["src/**/*.ts!", "build/*.js"]
}Enable with CLI:
knip --productionWhat's Included
entryandprojectpatterns suffixed with!- Production
entrypatterns from plugins (Next.js, Remix) - Only the
startscript from package.json - Excludes exports marked with
@internal
Note
The production run does not replace the default run. Run either or both separately.
Test Files and Helpers
Use negated patterns for mocks/helpers:
{
"entry": ["src/index.ts!"],
"project": ["src/**/*.ts!", "!src/test-helpers/**!"]
}Strict Mode
knip --production --strictAdds:
- Workspace isolation verification
peerDependenciesin unused/unlisted detection- Type-only imports in
dependenciesreporting
--strict implies --production.
Types
Exclude type-related issues:
knip --production --exclude typesFeatures
| Name | Description | Path |
|---|---|---|
| Auto-fix | Automatically removes unused code | auto-fix.md |
| Catalogs | Define dependency version ranges once and reference them across workspaces in a monorepo | catalogs.md |
| Compilers | Projects may have non-JS/TS source files requiring compilation | compilers.md |
| Custom Elements | Automatically recognizes custom element class registrations under tag names | custom-elements.md |
| Integrated Monorepos | Multiple projects within a single package.json, with configuration files distributed throughout | integrated-monorepos.md |
| Monorepos & Workspaces | Workspaces are directories with a package.json | monorepos-and-workspaces.md |
| Production Mode | Focuses exclusively on shipped code, excluding config, test, and Storybook files | production-mode.md |
| Reporters & Preprocessors | Built-in reporters for various output formats | reporters.md |
| Rules & Filters | Fine-grained control to include or exclude reported issue types | rules-and-filters.md |
| Script Parser | Analyzes shell commands and scripts to identify dependencies and entry files | script-parser.md |
| Source Mapping | Resolves mapping based on tsconfig.json settings | source-mapping.md |
Reporters & Preprocessors
Source: https://knip.dev/features/reporters
Built-in Reporters
| Reporter | Description |
|---|---|
symbols | Default reporter |
compact | Compact output |
codeowners | CODEOWNERS-based grouping |
json | Machine-readable JSON |
codeclimate | Code Climate format |
markdown | Markdown tables |
disclosure | Collapsible HTML details |
github-actions | PR annotations |
Usage: knip --reporter compact
JSON Reporter
knip --reporter jsonStructure: per-file objects with file, owners, dependencies, devDependencies, exports, types, enumMembers, duplicates.
GitHub Actions Reporter
knip --reporter github-actionsProduces annotations in pull requests.
Markdown Reporter
Generates tables organized by issue type with Name, Location, Severity columns.
Disclosure Reporter
Creates collapsible <details><summary> HTML elements.
CodeClimate Reporter
Generates Code Climate Report JSON format with type, check_name, description, categories, location, severity, fingerprint.
Custom Reporters
Local
type Reporter = async (options: ReporterOptions) => void;ReporterOptions includes: report, issues, counters, configurationHints, cwd, isProduction, options.
knip --reporter ./my-reporter.tsExternal
knip --reporter [pkg-name]Invokes default export from the package's main script.
Preprocessors
Execute post-analysis to modify results before reporters:
type Preprocessor = async (options: ReporterOptions) => ReporterOptions;knip --preprocessor ./preprocess.tsSupports local files and npm packages. Can be repeated.
Rules & Filters
Source: https://knip.dev/features/rules-and-filters
Filters
Include or exclude reported issue types:
knip --include files --include dependencies
knip --include files,dependencies
knip --include files --exclude enumMembers,duplicatesShorthands
| Shorthand | Includes |
|---|---|
--dependencies | dependencies, devDependencies, optionalPeerDependencies, unlisted, binaries, unresolved, catalog |
--exports | exports, types, enumMembers, namespaceMembers, duplicates |
--files | files |
Rules
Fine-grained control via configuration:
| Value | Printed | Counted | Description |
|---|---|---|---|
"error" | Yes | Yes | Includes the issue type |
"warn" | Yes | No | Faded color, doesn't count |
"off" | No | No | Excludes the issue type |
{
"rules": {
"files": "warn",
"duplicates": "off"
}
}When dependencies is included, devDependencies and optionalPeerDependencies can be separately configured as "warn".
Rules vs. Filters
- Filters: CLI-focused, shorthand syntax, usable in CLI and config
- Rules: Fine-grained
"warn"option, config-only, modeled after ESLint
Script Parser
Source: https://knip.dev/features/script-parser
Overview
Knip analyzes shell commands and scripts to identify dependencies, entry files, and configuration files. Scripts are parsed statically without execution.
package.json Parsing
Examines main, bin, exports, and scripts fields:
{
"main": "index.js",
"exports": {
"./lib": { "import": "./dist/index.mjs", "require": "./dist/index.cjs" }
},
"bin": { "program": "bin/cli.js" },
"scripts": {
"build": "rollup src/entry.ts",
"start": "node --loader tsx server.ts"
}
}Identified entry files: index.js, dist/index.mjs, dist/index.cjs, bin/cli.js, src/entry.ts, server.ts
Exclusions
Files matching .gitignore or ignore option are excluded. Scripts without standard extensions aren't processed.
CLI Arguments
Detected:
- First positional arguments as entry files
-c/--configas configuration files--require,--loader,--importas dependencies
Example: "start": "node --import tsx/esm run.ts" → tsx as dependency, run.ts as entry.
Scripts in Configuration Files
Plugins use the parser for:
- GitHub Actions:
runfields in workflow files - Husky & Lefthook: Git hooks and
lefthook.yml - Lint Staged: Command values
- Nx: Task executors and
nx:run-commands - Release It: Hook commands
Source Code Analysis
Template tag scripts in specialized libraries:
bun
import { $ } from 'bun';
await $`bun boxen I ❤ unicorns`;execa
await $({ stdio: 'inherit' })`c8 node hydrate.js`;zx
await $`node scripts/parse.js`;Source Mapping
Source: https://knip.dev/features/source-mapping
Overview
Knip is mostly interested in source code. Analyzing build artifacts hurts performance and leads to false positives. Source mapping resolves this by mapping based on tsconfig.json settings.
Example: package.json
Given tsconfig.json with outDir: "dist":
- Files NOT in
outDir→ included as entry files directly - Files IN
dist→ mapped to source equivalents insrc
Extension list: js, mjs, cjs, jsx, ts, tsx, mts, cts.
Using ./dist/*.js means all files matching ./src/**/*.{js,ts} are added as entry files.
Example: Monorepo
When importing from @org/shared with "main": "dist/index.js":
1. Module resolver locates dist/index.js 2. Knip maps to source file using tsconfig.json outDir 3. If src/index.ts exists, uses that instead
Limitations
- Currently only works based on
tsconfig.json - Projects may require compiling artifacts to
outDirbefore Knip can apply source mapping
Configuring Project Files
Source: https://knip.dev/guides/configuring-project-files
Overview
entry and project file patterns are fundamental to Knip.
- Start with defaults, add targeted
entryoverrides when necessary - Use
projectpatterns with negations to define analysis scope - Use production mode to exclude non-production files
- Reserve
ignorefor suppressing issues in specific files, not excluding from analysis
Entry Files
Avoid adding excessive files as entry points:
1. Knip does not report unused exports in entry files by default 2. Proper pattern configuration identifies unused files/exports more effectively
Unused Files Detection
unused files = project files - (entry files + resolved files)Negated Patterns
{"entry": ["src/routes/*.ts", "!src/routes/_*.ts"]}Source boundaries:
{
"entry": ["src/index.ts"],
"project": ["src/**/*.ts", "!src/exclude/**"]
}Best Practices
Incorrect: Using ignore for build artifacts or negating patterns in entry to exclude tests.
Recommended: Define project boundaries with project patterns.
Production Mode
Use knip --production instead of filtering tests through ignore:
{
"entry": ["src/index.ts!"],
"project": ["src/**/*.ts!", "!src/test-helpers/**!"]
}Defaults
{
"entry": [
"{index,cli,main}.{js,cjs,mjs,jsx,ts,cts,mts,tsx}",
"src/{index,cli,main}.{js,cjs,mjs,jsx,ts,cts,mts,tsx}"
],
"project": ["**/*.{js,cjs,mjs,jsx,ts,cts,mts,tsx}!"]
}Contributing
Source: https://knip.dev/guides/contributing
How to Contribute
1. Spread awareness — share Knip with others 2. Star the repository — GitHub stars at the project repo 3. File issues — bug reports with reproduction steps 4. Submit pull requests — code contributions welcome
Plugin Development
Writing a plugin is a great way to get started contributing.
Documentation
CONTRIBUTING.md— contribution guidelinesDEVELOPMENT.md— setup and development instructions
Both in the .github/ directory on GitHub.
Philosophy
The main goal is to keep projects clean & tidy. Everything contributing to that goal is welcome.
Handling Issues
Source: https://knip.dev/guides/handling-issues
Overview
Formula: unused files = project files - (entry files + resolved files)
Unused Files
Missing Generated Files
Compile/generate files before running Knip so imports resolve properly.
Dynamic Import Specifiers
const entry = await import(path.join(baseDir, 'entry.ts'));Fix: Add the file to entry patterns.
Unsupported Script Arguments
Fix: Add files to entry patterns.
Unsupported File Formats
HTML with script references need explicit config or an .html compiler.
Missing Plugin
Tools without Knip plugins have config files reported as unused. Fix: Create a plugin or use entry workarounds.
Incomplete Plugin
Override plugin config or submit PRs.
TypeScript Path Aliases in Monorepos
Use workspace packages as dependencies instead:
{ "dependencies": { "@org/common": "workspace:*" } }Auto-Mocking or Auto-Imports
Frameworks with auto-features (Jest, Nuxt) need extended entry patterns.
Unused Dependencies
Missing/Incomplete Plugins
Improve/create plugins or use ignoreDependencies.
Dependencies Named After Builtins
Packages named buffer/process → add to ignoreDependencies.
Conditional Dependencies
if (process.env.REPORT_PORTAL_ENABLED) {
reporters.push(['@reportportal/agent-js-playwright', config]);
}Fix: ignoreDependencies.
Bundled Types
Modern packages include type definitions. Remove separate @types/... packages.
Unlisted Dependencies
Transitive dependencies imported directly → install explicitly.
Unlisted Binaries
Use full package names with npx (e.g., npx @commitlint/cli not npx commitlint).
Unresolved Imports
Template Strings
import(\./${value}.ts\) cannot be resolved → add to entry or ignoreDependencies.
Extensionless Imports
Some non-standard extensions like .svg aren't recognized.
Unrecognized Path Aliases
Knip only recognizes TS config and knip.json paths, not Webpack/Vite aliases → configure in knip.json or ignoreUnresolved.
Unused Exports
Namespace Enumerations
Namespace used in enumeration patterns → all exports considered used. Enable nsExports to disable heuristic.
External Libraries
Exports consumed through external APIs may not be recognized.
Excluding from Reports
Options: ignoreExportsUsedInFile, JSDoc tags, add to entry, re-export from entry files.
Missing Unused Exports
Entry file exports not reported by default. Non-standard extensions need compilers.
Enum/Namespace Members
Reported by default. Disable: --exclude enumMembers or JSDoc tags.
Issue Reproduction
Source: https://knip.dev/guides/issue-reproduction
Overview
Open an issue on GitHub to help improve Knip.
Keep It Minimal
Create minimal source code and configuration to reproduce issues:
- Reduces unrelated context
- Optimizes shared understanding
- Establishes a contract for fixing
- Creates fixtures for testing
Useful supplements: screenshots, videos, code snippets, log output, repo links.
Before Opening an Issue
- Use the latest version
- Read relevant documentation
- Search existing issues
- Check known issues list
- File single issues at a time
Templates
CodeSandbox and StackBlitz templates available for:
- Basic project setup
- Monorepo configuration
Alternatives
- Public GitHub/GitLab repositories
- Pull requests with test fixtures in the Knip repo
Namespace Imports
Source: https://knip.dev/guides/namespace-imports
Overview
When using import * as NS, all exports become namespace members. The intention of export usage is not always clear.
Property Access Matters
If at least one reference to a property like NS.version is found, individual exports are considered separately.
Default Heuristic
- References without property access → all exports considered used
- Otherwise → exports evaluated individually
All Exports Considered Used
These patterns mark all exports as used:
{ ...NS }(spreading){ NS }(shorthand)NS(direct assignment)typeof NS(type operation)export { NS }(re-export)
Individual Evaluation
When NS.start is accessed alongside send(NS), the end export can be flagged as unused.
Configuration
Override behavior:
knip --include nsExportsOr include "nsExports" (and optionally "nsTypes") in configuration.
Performance
Source: https://knip.dev/guides/performance
Cache
knip --cacheConsecutive runs are 10-40% faster. Cache based on file modification time + size.
Ignoring Files
ignore patterns: files are still analyzed but excluded from report. To exclude from analysis, use negated entry/project patterns instead.
Metrics
knip --performanceShows execution data for expensive functions like findReferences.
ignoreExportsUsedInFile
Introduces 0.25%-10% overhead. Measure with:
knip --performance-fn hasRefsInFileLast Resort
For severe performance issues, lint individual workspaces.
Guides
| Name | Description | Path |
|---|---|---|
| Configuring Project Files | entry and project file patterns are fundamental to Knip. | configuring-project-files.md |
| Contributing | How to contribute to the Knip project. | contributing.md |
| Handling Issues | Formula for detecting unused files and resolving common issues. | handling-issues.md |
| Issue Reproduction | Open an issue on GitHub to help improve Knip. | issue-reproduction.md |
| Namespace Imports | When using import * as NS, all exports become namespace members. | namespace-imports.md |
| Performance | Cache and performance optimization techniques for Knip. | performance.md |
| Troubleshooting | Debug mode and trace options for troubleshooting issues. | troubleshooting.md |
| Using Knip in CI | Knip exits with code 1 when issues are detected, ideal for CI. | using-knip-in-ci.md |
| Working with CommonJS | CommonJS uses require() and module.exports. | working-with-commonjs.md |
Troubleshooting
Source: https://knip.dev/guides/troubleshooting
Lint Issues
Knip reports lint issues about unused code. Exit code 1 = successful execution with issues detected. See Handling Issues guide.
Exceptions
Knip throws exceptions for errors. Exit code 2 = exception occurred. Check Known Issues for workarounds.
Debug Mode
knip --debugShows:
- Included workspaces
- Configuration per workspace
- Enabled plugins per workspace
- Glob patterns and matching file paths
- Plugin config file paths and found dependencies
- Compiled non-standard source files
Trace Options
knip --trace
knip --trace-file [path]
knip --trace-export [name]
knip --trace-dependency [name]- Accepts exact strings or regex patterns
- Use
--workspace [filter]for filtering - Legend: ✓ (contains import), x (not imported), ◯ (entry file)
Using Knip in CI
Source: https://knip.dev/guides/using-knip-in-ci
Overview
Knip exits with code 1 when issues are detected, ideal for CI.
GitHub Actions Example
name: Lint project
on: push
jobs:
knip:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: npm install --ignore-scripts
- run: npm run knipRecommendations
1. Caching: --cache (stored at ./node_modules/.cache/knip) 2. Reporting: Use --reporter github-actions for PR annotations 3. Dual Execution: Run both standard and production mode 4. Output Config: --treat-config-hints-as-errors, --no-exit-code 5. Automation: CI applies --no-progress automatically
Working with CommonJS
Source: https://knip.dev/guides/working-with-commonjs
Overview
CommonJS uses require() and module.exports. Knip works with CommonJS without requiring ESM or tsconfig.json.
Challenge
Dynamic nature creates ambiguity about default vs. named exports.
Named Exports
Key Assignment
const B = function () {};
module.exports.A = { option: true };
module.exports.B = B;Shorthand Object
const A = function () {};
const B = { option: true };
module.exports = { A, B };Any other assignment to module.exports is treated as a default export.
Import Patterns
Incorrect (reports as unused)
const DefaultImport = require('./common.js');
const runtime = [DefaultImport.A, DefaultImport.B];Correct
const { A, B } = require('./common.js');Alternative
const runtime = [require('./common.js').A];Default Export Conversion
Adding non-shorthand property converts to single default export:
module.exports = { __esModule: true, A, B };__esModule follows the informal CJS/ESM interop standard.
Configuration
Source: https://knip.dev/overview/configuration
Defaults
Knip uses sensible defaults ("zero config"):
- Entry files:
index.{js,ts}andsrc/index.{js,ts} - Project files:
**/*.{js,ts}
Entry files are starting points for dependency and source file discovery.
Location
Configuration files are searched in order:
1. knip.json 2. knip.jsonc 3. .knip.json 4. .knip.jsonc 5. knip.ts 6. knip.js 7. knip.config.ts 8. knip.config.js 9. package.json (under "knip" property)
Custom path: knip --config path/to/knip.json
Customize
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"entry": ["src/index.ts", "scripts/{build,create}.js"],
"project": ["src/**/*.ts", "scripts/**/*.js"]
}- Custom values override defaults (not merge)
- Be specific with entry files
- Plugins are auto-enabled
What's Next
- Entry files documentation for deeper understanding
- Monorepos & workspaces for multi-package projects
- Production mode for production-only analysis
Features
Source: https://knip.dev/overview/features
Feature Overview
| Feature | Description |
|---|---|
| Auto-fix | --fix で未使用コードを自動修正 |
| Format | --format で修正後のファイルをフォーマット |
| Cache | --cache で連続実行を高速化 |
| Debug | --debug でトラブルシューティング |
| Performance | --performance で実行時間を計測 |
| Memory | --memory でメモリ使用量を表示 |
| JSDoc/TSDoc | タグでエクスポートを除外 |
| Script Parser | シェルスクリプトと package.json を解析 |
| Source Mapping | dist ファイルをソースにマッピング |
| Monorepo Support | ワークスペースがファーストクラス |
| Filter | --workspace でワークスペースをフィルタリング |
| Integrated Monorepo | 単一 package.json の統合モノレポ対応 |
| Rules & Filters | issue タイプごとの include/exclude |
| Config Hints | 設定ファイルのクリーンさを維持 |
| Compilers | Astro, MDX, Svelte, Vue, カスタムコンパイラ |
| Production Mode | 本番コードのみの厳密な lint |
| Plugins | 141 以上のプラグイン |
| Reporters | 複数の出力フォーマット |
| Watch Mode | ファイル変更をリアルタイム監視 |
| Trace | エクスポートの使用箇所を追跡 |
Getting Started
Source: https://knip.dev/overview/getting-started
Requirements
Knip v6 requires Node.js v20.19.0 or Bun.
Installation
Automated Setup (Recommended)
npm init @knip/config
pnpm create @knip/config
bun create @knip/config
yarn create @knip/configAfter setup, run Knip:
npm run knip
pnpm knip
bun knip
yarn knipManual Installation
npm install -D knip typescript @types/nodeAdd to package.json:
{
"scripts": {
"knip": "knip"
}
}typescript and @types/node are peer dependencies to increase compatibility.
Without Installation
npx knip
pnpm dlx knip
bunx knipManaging Output
For large codebases, limit displayed issues:
knip --max-show-issues 5Do not use the ignore option to suppress output. Instead, refer to Configuring Project Files for proper setup.
overview
| Name | Description | Path |
|---|---|---|
| Configuration | Knip uses sensible defaults ("zero config"): | configuration.md |
| Features | Feature Overview | features.md |
| Getting Started | Knip v6 requires Node.js v20.19.0 or Bun. | getting-started.md |
| Screenshots & Videos | --watch と --fix オプションを VS Code 内で使用するデモ。任意のターミナル環境で… | screenshots-videos.md |
Screenshots & Videos
Source: https://knip.dev/overview/screenshots-videos
Watch & Auto-Fix
--watch と --fix オプションを VS Code 内で使用するデモ。任意のターミナル環境で動作する。
関連: --watch CLI パラメータ、Auto-fix 機能ガイド
Trace
Export Tracing
特定のエクスポート(例: mapIterator)の使用箇所をトレースする機能。
File Tracing
複雑な import/re-export チェーンを一目で把握できる。
関連: トラブルシューティングガイドの Trace セクション
Performance
--performance 出力のスクリーンショット。Knip 自体のコードベースでのパフォーマンス計測結果を表示。
関連: --performance CLI 引数
CLI Arguments
Source: https://knip.dev/reference/cli
General
| Flag | Description |
|---|---|
--help / -h | ヘルプ表示 |
--version / -V | バージョン表示 |
--no-progress / -n | プログレス非表示(CI では自動) |
--config [file] / -c | 設定ファイルパス指定 |
--use-tsconfig-files | tsconfig.json で project files を定義 |
--tsConfig [file] / -t | 代替 tsconfig ファイル指定 |
knip-bun | Bun ランタイムで実行 |
NO_COLOR | カラー出力無効化(環境変数) |
Mode
| Flag | Description |
|---|---|
--cache | 連続実行を 10-40% 高速化 |
--cache-location | キャッシュ保存先(default: ./node_modules/.cache/knip) |
--include-entry-exports | エントリーファイルの未使用 exports をレポート |
--no-gitignore | .gitignore を無視 |
--production / -p | 本番ソースのみ lint |
--strict / -s | ワークスペース分離、production を暗黙的に含む |
--watch / -w | ファイル変更を監視 |
Scope
| Flag | Description |
|---|---|
--workspace [filter] / -W | ワークスペース選択 |
--directory [dir] / -D | 実行ディレクトリ変更 |
--exclude | issue タイプを除外 |
--include | issue タイプを含める |
--dependencies | 依存関係 issue のショートカット |
--exports | エクスポート issue のショートカット |
--files | ファイル issue のショートカット |
--tags | JSDoc/TSDoc タグでフィルタ(+/- 記法) |
Issue types: files, dependencies, unlisted, unresolved, exports, nsExports, types, nsTypes, enumMembers, namespaceMembers, duplicates, catalog
Fix
| Flag | Description |
|---|---|
--fix / -f | 自動修正 |
--fix-type | 修正対象を限定(comma-separated) |
--allow-remove-files | ファイル削除を許可 |
--format / -F | 修正後にフォーマッター実行 |
Output
| Flag | Description |
|---|---|
--preprocessor [file] | プリプロセッサ指定(繰り返し可) |
--preprocessor-options [json] | プリプロセッサに JSON オプション |
--reporter [reporter] | 出力形式(繰り返し可) |
--reporter-options [json] | レポーターに JSON オプション |
--no-config-hints | 設定ヒント非表示 |
--no-tag-hints | タグ関連ヒント非表示 |
--treat-config-hints-as-errors | 設定ヒントをエラーに |
--max-issues | 最大 issue 数(超過で exit 1) |
--max-show-issues | 表示 issue 数の制限 |
--no-exit-code | 常に exit 0 |
Exit codes: 0 (no issues), 1 (issues found), 2 (error/exception)
Troubleshooting
| Flag | Description |
|---|---|
--debug / -d | 詳細デバッグ出力 |
--memory | メモリ使用量表示 |
--memory-realtime | リアルタイムメモリログ |
--performance | 実行時間統計 |
--duration / -u | 合計実行時間表示 |
--performance-fn | 単一関数のプロファイル |
--trace | エクスポートの import 箇所表示 |
--trace-dependency [name] | パッケージ/バイナリ参照をトレース |
--trace-export [name] | エクスポート名をトレース |
--trace-file [path] | ファイルのエクスポートをトレース |
Configuration Hints
Source: https://knip.dev/reference/configuration-hints
Overview
Configuration hints maintain clean config files and minimize drift. Warnings by default; suppress with --no-config-hints or treat as errors with --treat-config-hints-as-errors. Tag-related hints can be suppressed with --no-tag-hints or escalated with treatTagHintsAsErrors.
Categories
1. Unconfigured Projects
Too many unused files → add/refine entry/project patterns.
2. Unconfigured Workspaces
Missing workspace config in monorepos:
{
"workspaces": {
"packages/app": {
"entry": ["src/App.tsx"],
"project": ["src/**/*.ts"]
}
}
}3. Top-level Entry/Project in Monorepos
Root-level entry/project ignored in monorepos → move to workspaces objects.
4. Unused Entry in Ignore Group
Entry in ignoreWorkspaces/ignoreDependencies/ignoreBinaries/ignoreUnresolved no longer needed → remove.
5. Useless Patterns
Glob patterns matching no files → modify or delete.
6. Redundant Patterns
Patterns already covered by defaults or plugins → remove.
7. Missing Package Entry File
package.json entry file doesn't exist → refine or remove.
Configuration
Source: https://knip.dev/reference/configuration
JSON Schema
{ "$schema": "https://unpkg.com/knip@6/schema.json" }JSONC (comments/trailing commas):
{ "$schema": "https://unpkg.com/knip@6/schema-jsonc.json" }Project Configuration
entry
Array of glob patterns for entry files. Prefix ! for negation.
{ "entry": ["src/index.ts", "scripts/*.ts", "!scripts/except.ts"] }project
Array of glob patterns for project files.
{ "project": ["src/**/*.ts", "scripts/**/*.ts"] }paths
Import aliases. Automatically includes TypeScript compilerOptions.paths.
{
"paths": {
"@lib": ["./lib/index.ts"],
"@lib/*": ["./lib/*"]
}
}Workspaces
Individual workspace configs support all options except: exclude/include, ignoreExportsUsedInFile, ignoreWorkspaces, workspaces.
Plugins
{
"mocha": { "config": "config/mocha.config.js", "entry": ["**/*.spec.js"] },
"playwright": true,
"webpack": false
}- Override
config/entrylocation true: force-enablefalse: disable
Rules & Filters
rules
{ "rules": { "files": "warn", "duplicates": "off" } }include / exclude
Filter issue types.
tags
{ "tags": ["-lintignore"] }+ (include, default) / - (exclude). @ prefix optional.
treatConfigHintsAsErrors
{ "treatConfigHintsAsErrors": true }treatTagHintsAsErrors
{ "treatTagHintsAsErrors": true }Ignore Issues
ignore
Avoid using. Better solutions usually exist.
{ "ignore": ["!src/dir/**"] }ignoreFiles
Exclude from "Unused files" only (still analyzed for other issues).
{ "ignoreFiles": ["src/generated/**", "fixtures/**"] }ignoreBinaries
{ "ignoreBinaries": ["zip", "docker-compose", "pm2-.+"] }ignoreDependencies
{ "ignoreDependencies": ["hidden-package", "@org/.+"] }ignoreMembers
{ "ignoreMembers": ["render", "on.+"] }ignoreUnresolved
{ "ignoreUnresolved": ["ignore-unresolved", "#virtual/.+"] }ignoreWorkspaces
{ "ignoreWorkspaces": ["packages/go-server", "packages/flat/*"] }ignoreIssues
{
"ignoreIssues": {
"src/generated/**": ["exports", "types"],
"**/*.generated.ts": ["exports", "enumMembers"]
}
}Exports
ignoreExportsUsedInFile
{ "ignoreExportsUsedInFile": true }Fine-grained:
{ "ignoreExportsUsedInFile": { "interface": true, "type": true } }includeEntryExports
{ "includeEntryExports": true }Reports unused exports in entry source files (not config files).
Compilers
Only in dynamic config (.js/.ts), not JSON.
Suffix ! on ignore patterns enables production-only mode.
Dynamic Configuration
Source: https://knip.dev/reference/dynamic-configuration
TypeScript
import type { KnipConfig } from 'knip';
const config: KnipConfig = {
entry: ['src/index.ts'],
project: ['src/**/*.ts'],
};
export default config;JavaScript
/** @type {import('knip').KnipConfig} */
const config = {
entry: ['src/index.ts'],
project: ['src/**/*.ts'],
};
export default config;Function-Based
TypeScript
import type { KnipConfig } from 'knip';
const config = async (): Promise<KnipConfig> => {
const items = await fetchRepoInfo();
return {
entry: ['src/index.ts', ...items],
project: ['src/**/*.ts'],
};
};
export default config;JavaScript
const config = async () => ({
entry: ['src/index.ts'],
project: ['src/**/*.ts'],
});
export default config;FAQ
Source: https://knip.dev/reference/faq
Why Should I Bother?
Configuring Knip properly gives absolute confidence in your codebase. Delete dead code, remove unused dependencies, refactor with certainty.
Common Pitfalls
- Configuration Hints: Critical for building healthy module graphs
- Ignore Patterns:
ignoresuppresses reporting but doesn't exclude from analysis. Useprojectpatterns instead - Excluding Tests: Use production mode, not ignore patterns
- Auto-fix: Don't run
--fixbefore configuration is complete
Knip vs. ESLint
ESLint analyzes files separately. Knip lints projects as a whole.
Knip vs. Tree-shaking
Tree-shaking operates at build time on bundles. Knip is a development-phase linter. Complementary tools.
Plugins
Plugins prevent configuration burden by adding entry files and parsing configuration files intelligently.
Building the Graphs
Entry File Sources
- Default locations (
index.js,src/index.ts) package.jsonfields:main,bin,exports- Plugin-configured locations
- Config files and their contents
- Dynamic imports,
require.resolve(),import.meta.resolve() - Template string scripts (execa, bun, zx)
package.jsonscripts, CI workflow files
Source File Analysis
Uses oxc-parser for AST analysis of imports, exports, namespace properties, require.resolve, and template strings.
Module Resolution
Custom resolver (oxc-resolver) supporting non-standard extensions, path aliases, exports maps, self-references, and source code resolution.
Non-standard Imports
Strips prefixes/suffixes from specifiers like "./icon.svg?raw" and webpack loader syntax.
TypeScript
- Workspaces vs Projects: Workspaces have
package.json; projects havetsconfig.json - ts.findReferences: Not used — heavy, per-symbol, single-program scope
- Path Aliases for Workspaces: Use dependencies in
package.jsoninstead - tsconfig.json Location:
--tsConfigfor root; pluginconfigper-workspace
Compilers
Knip includes regex-based extractors for Astro, MDX, Svelte, Vue (not actual compilers). Override with real compilers for proper export detection.
Production Mode Default
Both modes have merits. Production catches dead production code (UX). Default catches more including tooling (DX).
Integrations
Source: https://knip.dev/reference/integrations
VS Code Extension
Official extension:
- Inline warnings for unused dependencies, exports, files
- Hover information with import/usage locations
- Tree views for imports/exports
- Contention detection (circular dependencies)
- Built-in MCP Server
Available on VS Code Marketplace and Open VSX Registry.
JetBrains Plugin
Community-maintained. Supports WebStorm, IntelliJ IDEA, etc. Powered by Knip Language Server.
MCP Server
Enables coding agents to configure Knip automatically.
npx @knip/mcpVS Code extension includes this by default.
Language Server
Underlying technology for IDE integrations. Builds the full module graph and provides a graph explorer session.
Issue Types
Source: https://knip.dev/reference/issue-types
Core Issues
| Type | Filter | Description | Auto-fix |
|---|---|---|---|
| Unused files | files | No reference found | Yes |
| Unused dependencies | dependencies | No reference to dependency | Yes |
| Unused devDependencies | dependencies | No reference to devDependency | Yes |
| Referenced optional peerDependencies | dependencies | Optional peer dep is used | - |
| Unlisted dependencies | unlisted | Used but not in package.json | - |
| Unlisted binaries | binaries | Binaries not in package.json | - |
| Unused catalog entries | catalog | No reference to catalog entry | Yes |
| Unresolved imports | unresolved | Cannot resolve specifier | - |
Export Issues
| Type | Filter | Description | Auto-fix |
|---|---|---|---|
| Unused exports | exports | No reference to export | Yes |
| Unused exported types | types | No reference to type | Yes |
| Exports in used namespace | nsExports | Namespace used, export unused | Yes |
| Types in used namespace | nsTypes | Namespace used, type unused | Yes |
| Unused enum members | enumMembers | No reference to member | Yes |
| Unused namespace members | namespaceMembers | No reference to member | Yes |
| Duplicate exports | duplicates | Exported more than once | - |
JSDoc & TSDoc Tags
Source: https://knip.dev/reference/jsdoc-tsdoc-tags
Overview
JSDoc/TSDoc tags create exceptions for unused/duplicate exports without new syntax or configuration.
Note: Adding tags to hide issues is usually not recommended.
Format
JSDoc comments must start with /** (not //).
Tags
Arbitrary Tags
Custom tags like @lintignore:
knip --tags=-lintignore,-internal- excludes, + includes. When excluded tags become unnecessary, Knip reports a "tag hint".
@public
Prevents reporting unused exports in non-entry files. Also creates exceptions with --include-entry-exports.
@internal
Marks exports for internal use only. Exempted from production mode reporting.
@alias
Prevents duplicate export warnings:
export const Component = () => {};
/** @alias */
export default Component;@beta
Functions identically to @public.
Known Issues
Source: https://knip.dev/reference/known-issues
1. Exceptions from Config Files
Plugins may throw exceptions when loading config files in Knip's environment.
Workarounds:
- Set path aliases for module resolution errors
- Supply missing environment variables:
KEY=VAL knip - Use
node --env-file .env $(which knip) - Disable file loading:
vite: { config: [] } - Add as entry file for static analysis
- Disable the plugin entirely
- Ignore the workspace as last resort
2. Path Aliases in Config Files
TypeScript path aliases may fail with "Cannot find module".
Workarounds:
- Convert to relative paths
- Inject module support:
NODE_OPTIONS="--import tsx" knip - Use Bun with knip-bun
3. Nx Daemon
"Daemon process terminated and closed the connection"
Solution: NX_DAEMON=false knip
Plugins (155)
Source: https://knip.dev/reference/plugins
Overview
Plugins activate automatically when their associated package appears in package.json dependencies. Each plugin handles configuration files, entry file patterns, and CLI arguments.
Configuration
{
"pluginName": { "config": "path/to/config", "entry": ["pattern"] },
"pluginName": true,
"pluginName": false
}Complete Plugin List
Angular, Astro, Astro DB, astro-og-canvas, Ava, Babel, Biome, bumpp, Bun, c8, Capacitor, Catalyst, Changelogen, Changelogithub, Changesets, Commitizen, commitlint, Convex, create-typescript-app, CSpell, Cucumber, Cypress, Danger, dependency-cruiser, Docusaurus, dotenv, Drizzle, Eleventy, ESLint, execa, Expo, Expressive Code, FAST, Gatsby, GitHub Action, GitHub Actions, glob, GraphQL Codegen, Hardhat, husky, i18next Parser, Jest, Karma, Knex, Ladle, Lefthook, lint-staged, LintHTML, Lit, lockfile-lint, Lost Pixel, markdownlint, MDX, mdxlint, Metro, Mocha, moonrepo, Mock Service Worker, nano-spawn, Nano Staged, Nest, Netlify, Next.js, next-intl, Next.js MDX, Nitro, Node.js, node-modules-inspector, nodemon, npm-package-json-lint, Nuxt, Nx, nyc, oclif, openapi-ts, orval, Oxfmt, Oxlint, Panda CSS, Parcel, Payload CMS, pino, Playwright, Playwright for components, playwright-test, Plop, pm2, pnpm, PostCSS, Preconstruct, Prettier, Prisma, Qwik, Raycast, React Cosmos, React Email, React Native, React Router, Relay, Release It!, Remark, Remix, Rolldown, Rollup, Rsbuild, Rslib, Rspack, Rstest, Sanity, Semantic Release, Sentry, Serverless Framework, simple-git-hooks, size-limit, SST, Starlight, Stencil, Storybook, Stryker, Stylelint, Svelte, @sveltejs/package, SvelteKit, SVGO, SVGR, SWC, Syncpack, Tailwind, TanStack Router, Taskfile, Travis CI, ts-node, tsdown, tsup, tsx, TypeDoc, TypeScript, unbuild, UnoCSS, Vercel, Vercel OG, Vike, Vite, VitePress, Vitest, Vue, WebdriverIO, webpack, Wireit, Wrangler, WXT, xo, Yarn, yorkie, zx
Individual plugin pages: https://knip.dev/reference/plugins/[name]
Reference
| Name | Description | Path |
|---|---|---|
| CLI Arguments | 汎用・モード・スコープ・修正系フラグ一覧(--help / --version / --cache / --watch 等)。 | cli.md |
| Configuration | entry / project / paths の基本設定・JSON Schema・ワークスペース設定。 | configuration.md |
| Configuration Hints | 設定ファイル内の問題検出・改善ヒント(unconfigured projects/workspaces 等)。 | configuration-hints.md |
| Dynamic Configuration | TypeScript / JavaScript / async 関数ベースの動的設定方法。 | dynamic-configuration.md |
| FAQ | 導入理由・よくある落とし穴・他ツール比較(ESLint / tree-shaking)。 | faq.md |
| Integrations | VS Code 拡張・JetBrains プラグイン・MCP Server・Language Server。 | integrations.md |
| Issue Types | 検出可能な issue 一覧(unused files / dependencies / exports / types 等)。 | issue-types.md |
| JSDoc & TSDoc Tags | @public / @internal / @alias / @beta タグによる例外処理・カスタムタグ。 | jsdoc-tsdoc-tags.md |
| Known Issues | プラグイン読み込み例外・path alias 解決失敗・Nx daemon 問題のワークアラウンド。 | known-issues.md |
| Plugins (155) | 155 プラグイン一覧・自動有効化・設定オプション(config / entry)。 | plugins.md |
| Related Tooling | 補完ツール(ESLint / Biome / oxlint・circular dependencies 検出・technical debt)。 | related-tooling.md |
Related Tooling
Source: https://knip.dev/reference/related-tooling
Unused Imports & Variables
Knip focuses on exported values across files, not internal variables. Use:
- ESLint — find unused variables within files
- Biome — linting for unused code
- oxlint — unused variable identification
- remove-unused-vars — removes unused code within files more aggressively
Unused Properties
Knip cannot yet identify unused members of types, interfaces, or objects (including React props). Supported: unused enum/class members.
Circular Dependencies
- DPDM
- Madge
- skott
Technical Debt Cleanup
- e18e.dev — cleanup guidance
typescript
| Name | Description | Path |
|---|---|---|
| Unused Dependencies | Source: https://knip.dev/typescript/unused-dependencies | unused-dependencies.md |
| Unused Exports | Source: https://knip.dev/typescript/unused-exports | unused-exports.md |
Unused Dependencies
Source: https://knip.dev/typescript/unused-dependencies
Why Unused Dependencies Are Problematic
1. Bundle Impact: May end up in production bundle, increasing size and load times 2. Storage Waste: Consume space in node_modules, extend installation times 3. Tool Performance: Slow down linters and bundlers 4. Code Clarity: Create confusion in package.json 5. Maintenance Burden: Unnecessary upgrade complexity 6. Version Conflicts: Can cause compatibility issues 7. Security Concerns: Cause false security alerts 8. Licensing Issues: May impose restrictive terms 9. Transitive Dependencies: Bring additional unwanted packages
Finding and Removing
Knip locates unused dependencies through code analysis. Use --fix to auto-remove from package.json.
How Knip Works
Analyzes package.json, source code, and configuration files using plugins and compilers.
Additional Capabilities
- Missing Dependencies: Identifies packages used but not listed
- Monorepo Support: Handles workspaces and dependency relationships
- Dependency Type Separation: Distinguishes dependencies vs devDependencies
- Production Mode: Focus on production code only
- Package Manager Compatibility: npm, pnpm, Bun, Yarn
Unused Exports
Source: https://knip.dev/typescript/unused-exports
Why Unused Exports Are Problematic
1. Bundle Size: Increase sizes if not eliminated by tree-shaking 2. Code Clutter: Make codebases harder to navigate 3. Developer Confusion: Mislead about actual code usage 4. Refactoring Difficulty: Complicate maintenance 5. Tool Performance: Slow down bundlers, linters, type checkers 6. Dead Code Risk: May represent abandoned code
Finding Unused Exports
Knip analyzes the codebase, identifies exports not imported anywhere, and reports them.
How Knip Identifies
Uses both static and dynamic analysis, examining import statements and code patterns. Supports CommonJS and ES Modules.
Auto-fix
--fix flag automatically removes unused exports from source files.
Large Codebases
Supports monorepo structures with workspaces.
Knip vs. ESLint
ESLint finds unused imports/variables within individual files. Knip analyzes the entire project through comprehensive module graph construction.
Argument Parsing
Source: https://knip.dev/writing-a-plugin/argument-parsing
Overview
Customize how CLI arguments are processed for tool executables. Uses minimist-compatible options.
Configuration Options
alias
Argument aliases: { require: ['r'] } → -r as shorthand for --require.
args
Modify/filter arguments before parsing. Accepts function (args: string[]) => string[].
binaries
Executable names for the dependency. Default: plugin name.
{ binaries: ['tsc'] }boolean
Mark arguments as boolean type.
config
Arguments containing config file paths. Shorthand true sets alias, string, and config.
{ config: ['p'] } // handles -p tsconfig.lib.jsonfromArgs
Parse return value as new script:
{ fromArgs: ['exec'] } // nodemon --exec "node index.js"nodeImportArgs
Shorthand for Node import aliases:
{ import: ['r', 'experimental-loader', 'require', 'loader'] }positional
true to use first positional argument as entry point.
resolve
List of arguments to resolve to dependency or entry file:
{ resolve: ['plugin'] }resolveInputs
Function returning inputs from parsed arguments:
(parsed: ParsedArgs) => parsed['flag'] ? [toDependency('package')] : []string
Mark arguments as strings (prevents number conversion by minimist).
Inputs
Source: https://knip.dev/writing-a-plugin/inputs
Overview
Input functions communicate plugin findings to Knip. More precision → better results and performance.
Functions
toEntry
Entry points. Accepts absolute/relative paths with glob patterns.
toProductionEntry
Production entry points. Paths and glob patterns.
toProject
Project patterns. Supports negated and standard globs.
toDependency
Dependency in dependencies or devDependencies.
toProductionDependency
Production dependency in dependencies.
toDeferResolve
Defer specifier resolution. May resolve to dependency or entry file. Reports unresolved imports if unsuccessful.
toDeferResolveEntry
Like toDeferResolve but restricted to entry files only. Ignores unresolved inputs.
toConfig
Reference config files handled by other plugins. Example: Angular plugin referencing tsConfig in angular.json.
toBinary
Binary assignments from package.json bin declarations. Used by shell script parsers.
toAlias
Add path aliases to module resolver (same syntax as compilerOptions.paths).
Options
dir
Assign inputs to different workspaces (e.g., GitHub Actions in root).
optional
Flag dependency as not required (won't report as unlisted if absent).
allowIncludeExports
Enable reporting entry file exports as unused with --include-entry-exports. Works with toProductionEntry.
Writing A Plugin
| Name | Description | Path |
|---|---|---|
| Argument Parsing | Customize how CLI arguments are processed for tool executables. Uses minimist-compatible options. | ./argument-parsing.md |
| Inputs | Input functions communicate plugin findings to Knip. More precision → better results and performance. | ./inputs.md |
| Writing A Plugin | Plugins accomplish at least one of: Define entry file patterns, Find dependencies in configuration files | ./writing-a-plugin.md |
Writing A Plugin
Source: https://knip.dev/writing-a-plugin
Overview
Plugins accomplish at least one of: 1. Define entry file patterns 2. Find dependencies in configuration files
Basic Entry Plugin (Tailwind)
const title = 'Tailwind';
const enablers = ['tailwindcss'];
const isEnabled = ({ dependencies }) => hasDependency(dependencies, enablers);
const entry = ['tailwind.config.{js,cjs,mjs,ts}'];
const plugin = { title, enablers, isEnabled, entry };
export default plugin;Properties
- title: Display name
- enablers: Dependency names (regex supported) matched against
package.json - isEnabled: Function checking required dependencies
- entry: File patterns added as entry files
Config File Parsing (NYC)
const title = 'nyc';
const enablers = ['nyc'];
const isEnabled = ({ dependencies }) => hasDependency(dependencies, enablers);
const config = ['.nycrc', '.nycrc.{json,yml,yaml}', 'nyc.config.js', 'package.json'];
const resolveConfig = config => {
const extend = config?.extends ?? [];
const requires = config?.require ?? [];
return [extend, requires].flat().map(id => toDeferResolve(id));
};
const plugin = { title, enablers, isEnabled, config, resolveConfig };- config: Configuration file locations
- resolveConfig: Processes config values, returns entries/dependencies
Entry Pattern Customization (Mocha)
const entry = ['**/test/*.{js,cjs,mjs}'];
const resolveConfig = localConfig => {
const entryPatterns = localConfig.spec ? [localConfig.spec].flat() : entry;
return entryPatterns.map(id => toEntry(id));
};AST Processing (Astro)
const resolveFromAST = (program) => {
const componentPaths = getComponentPaths(program);
return [...production, ...componentPaths].map(id => toProductionEntry(id));
};resolveFromAST accesses dynamic configuration values not available in parsed objects.
Custom Resolution (Fallback)
const resolve = async options => {
return toDependency('troublesome', { optional: true });
};Creating New Plugins
cd packages/knip
npm create-plugin --name toolGenerates source, test files, and fixtures. Run tests:
node --test test/plugins/tool.test.tsSupported Config Formats
JSON, YAML, TOML, JavaScript, TypeScript, plain text.
Auto-fix
Automatically remove unused exports, dependencies, and files detected by knip.
# Remove unused exports and dependencies
knip --fix
# Also remove unused files (requires explicit opt-in)
knip --fix --allow-remove-files
# Fix only specific issue types
knip --fix-type exports,types
# Fix and auto-format with Biome/Prettier/dprint
knip --fix --formatBefore and after example for unused exports:
// Before
export const unused = 1;
export default class MyClass {}
// After (export keywords removed)
const unused = 1;
class MyClass {}Before and after for package.json dependencies:
// Before
{ "dependencies": { "rimraf": "*", "unused-dep": "*" } }
// After
{ "dependencies": { "rimraf": "*" } }Notes
- Always use version control (Git) before running
--fixto be able to review and undo changes --fix-typeaccepts:dependencies,exports,types,files,catalog- Auto-fix does NOT add unlisted/missing dependencies — install them separately after fixing
- After fixing dependencies, run
npm install(or equivalent) to update the lockfile
Basic Configuration
Configure entry and project file patterns in knip.json to define the analysis scope.
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"entry": ["src/index.ts", "scripts/{build,create}.js"],
"project": ["src/**/*.ts", "scripts/**/*.js"]
}Exclude specific paths with negated patterns:
{
"entry": ["src/routes/*.ts", "!src/routes/_*.ts"],
"project": ["src/**/*.ts", "!src/exclude/**"]
}Notes
- Custom
entryandprojectvalues override defaults, they do not merge - Default entry:
index.{js,ts}andsrc/index.{js,ts}; default project:**/*.{js,ts} - Config file is auto-detected:
knip.json,.knip.json,knip.ts,knip.config.ts, or"knip"key inpackage.json - Do not use
ignoreto exclude files from analysis; use negatedprojectpatterns instead
CI Integration
Run knip in CI to block merges when unused code or dependencies are detected.
# .github/workflows/knip.yml
name: Lint project
on: push
jobs:
knip:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: npm install --ignore-scripts
- run: npm run knipEnable GitHub Actions PR annotations:
knip --reporter github-actionsUse caching for faster runs:
knip --cacheRun both default and production mode in CI:
- run: npm run knip
- run: npm run knip -- --production --strictNotes
- Knip exits with code
1on any detected issue, which fails CI jobs automatically --no-progressis applied automatically in CI environments- Cache is stored at
./node_modules/.cache/knip; include this path in CI cache configuration - Use
--reporter github-actionsto get inline annotations on pull request diffs
Getting Started
Install knip and run it on a project to find unused files, exports, and dependencies.
# Automated setup (recommended)
npm init @knip/config
# Then run
npm run knip# Manual install
npm install -D knip typescript @types/node// package.json
{
"scripts": {
"knip": "knip"
}
}# Without installation
npx knipNotes
- Automated setup (
npm init @knip/config) createsknip.jsonand adds theknipscript topackage.json typescriptand@types/nodeare peer dependencies required for TypeScript analysis- Knip exits with code
1when issues are detected, making it CI-friendly by default - For large codebases, use
--max-show-issues 5to limit initial output
Ignore Patterns
Suppress false positives for generated files, conditional dependencies, and unresolved imports.
{
"ignoreFiles": ["src/generated/**", "fixtures/**"],
"ignoreDependencies": ["hidden-package", "@org/.+"],
"ignoreBinaries": ["zip", "docker-compose", "pm2-.+"],
"ignoreMembers": ["render", "on.+"],
"ignoreUnresolved": ["#virtual/.+"],
"ignoreIssues": {
"src/generated/**": ["exports", "types"],
"**/*.generated.ts": ["exports", "enumMembers"]
}
}Ignore exports used only within the same file:
{
"ignoreExportsUsedInFile": { "interface": true, "type": true }
}Notes
ignoreFilesexcludes files from "Unused files" reporting only; those files are still analyzed for other issue typesignoreDependenciesandignoreBinariesaccept regex patterns (e.g.,"@org/.+"matches all@org/*packages)- Prefer
ignoreIssuesoverignoreFileswhen you want to suppress specific issue types per file glob - Avoid using
ignore(the generic option) — targeted options likeignoreFilesorignoreDependenciesare almost always the right solution
JSDoc & TSDoc Tags
Annotate exports with JSDoc tags to control knip reporting without changing configuration files.
// Prevent reporting as unused in non-entry files
/** @public */
export function publicApi() {}
// Mark as internal — excluded from production mode reporting
/** @internal */
export function internalHelper() {}
// Prevent duplicate export warning
export const Component = () => {};
/** @alias */
export default Component;Use custom tags to selectively exclude exports:
# Exclude exports tagged with @lintignore or @internal
knip --tags=-lintignore,-internal/** @lintignore */
export const legacyExport = 'kept for compatibility';Notes
- JSDoc comments must start with
/**(not//or/*) for knip to recognize the tags @publicand@betaare functionally identical: both prevent unused export reporting and work with--include-entry-exports- Use the
tagsconfig option to define custom tag behavior persistently:{ "tags": ["-lintignore"] } - When a tag exclusion becomes unnecessary (the export is no longer unused), knip reports a "tag hint" to clean it up
Monorepo & Workspaces
Configure knip to analyze a monorepo with multiple workspace packages.
{
"workspaces": {
".": {
"entry": "scripts/*.js",
"project": "scripts/**/*.js"
},
"packages/*": {
"entry": "{index,cli}.ts",
"project": "**/*.ts"
},
"packages/cli": {
"entry": "bin/cli.js"
}
}
}Analyze a specific workspace only:
# By directory path
knip --workspace packages/my-lib
# By package name
knip -W @myorg/my-lib
# By glob, excluding one
knip --workspace @myorg/* --workspace '!@myorg/legacy'Skip specific workspaces entirely:
{
"ignoreWorkspaces": ["packages/go-server", "packages/flat/*"]
}Notes
- Workspaces are auto-discovered from
package.jsonworkspaces,pnpm-workspace.yaml, or theworkspacesobject inknip.json - Root-level
entry/projectkeys are ignored whenworkspacesis configured; use"."as the root workspace key --workspaceautomatically includes ancestor and dependent workspaces- For isolated workspace linting, combine
--workspacewith--production --strict
Output Formats
Select a built-in reporter or write a custom one to consume knip results in any format.
# Default symbols output
knip
# Compact single-line-per-file output
knip --reporter compact
# JSON for scripting or downstream tools
knip --reporter json
# Markdown tables
knip --reporter markdown
# GitHub Actions PR annotations
knip --reporter github-actionsWrite a custom local reporter:
// my-reporter.ts
import type { ReporterOptions } from 'knip';
export default async ({ issues }: ReporterOptions) => {
for (const [filePath, fileIssues] of Object.entries(issues.files)) {
console.log(filePath, fileIssues);
}
};knip --reporter ./my-reporter.tsNotes
- JSON output structure: per-file objects with
file,owners,dependencies,devDependencies,exports,types,enumMembers,duplicates --reporter github-actionsproduces inline annotations visible in pull request diff view- Custom reporters receive a
ReporterOptionsobject includingreport,issues,counters,configurationHints,cwd,isProduction - Use a preprocessor (
--preprocessor ./preprocess.ts) to transform results before the reporter receives them
Production Mode
Analyze only production code by excluding test files, config files, and devDependencies.
knip --productionMark patterns as production-only with the ! suffix:
{
"entry": ["src/index.ts!"],
"project": ["src/**/*.ts!", "!src/test-helpers/**!"]
}Strict mode adds workspace isolation and peer dependency checks:
knip --production --strictNotes
- Append
!to glob patterns to mark them as production-only;--productionthen analyzes only those patterns --strictimplies--productionand additionally verifies workspace isolation and reportspeerDependencies- The production run does not replace the default run; run both separately to get complete coverage
- Exclude type-related issues in production mode:
knip --production --exclude types
samples
| Name | Description | Path |
|---|---|---|
| Auto-fix | Automatically remove unused exports, dependencies, and files detected by knip. | auto-fix.md |
| Basic Configuration | Configure entry and project file patterns in knip.json to define the analysis scope. | basic-configuration.md |
| CI Integration | Run knip in CI to block merges when unused code or dependencies are detected. | ci-integration.md |
| Getting Started | Install knip and run it on a project to find unused files, exports, and dependencies. | getting-started.md |
| Ignore Patterns | Suppress false positives for generated files, conditional dependencies, and unresolved imports. | ignore-patterns.md |
| JSDoc & TSDoc Tags | Annotate exports with JSDoc tags to control knip reporting without changing configuration files. | jsdoc-tags.md |
| Monorepo & Workspaces | Configure knip to analyze a monorepo with multiple workspace packages. | monorepo-workspaces.md |
| Output Formats | Select a built-in reporter or write a custom one to consume knip results in any format. | output-formats.md |
| Production Mode | Analyze only production code by excluding test files, config files, and devDependencies. | production-mode.md |
| Rules & Filters | Control which issue types are reported and whether they cause CI failures. | rules-and-filters.md |
Rules & Filters
Control which issue types are reported and whether they cause CI failures.
Filter issue types via CLI flags:
# Report only unused files and dependencies
knip --include files,dependencies
# Exclude specific types from the report
knip --include files --exclude enumMembers,duplicates
# Shorthands
knip --dependencies # all dependency-related issues
knip --exports # all export-related issues
knip --files # unused files onlyConfigure severity levels per issue type in knip.json:
{
"rules": {
"files": "warn",
"duplicates": "off",
"devDependencies": "warn"
}
}Notes
"error"(default): issue is printed and counted toward the exit code"warn": issue is printed in faded color but does not increment the failure count"off": issue is completely suppressed- CLI
--include/--excludefilters are applied on top ofrules; userulesfor persistent team-wide configuration
ci
CI 環境での knip 実行コマンドと GitHub Actions 設定例。
CI での基本実行
knipCI 環境では --no-progress が自動的に適用される。exit code 1 で issue 検出を示す。
キャッシュ有効化(高速化)
knip --cacheデフォルトのキャッシュ保存先: ./node_modules/.cache/knip
GitHub Actions アノテーション付き出力
knip --reporter github-actionsPR 上にインラインアノテーションを表示する。
本番モードとの二重実行
knip
knip --productionデフォルトモードと本番モードを別々に実行することを推奨する。
設定ヒントをエラーとして扱う
knip --treat-config-hints-as-errorsGitHub Actions ワークフロー例
name: Lint project
on: push
jobs:
knip:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: npm install --ignore-scripts
- run: npm run knipGitHub Actions でキャッシュと本番モードを組み合わせた例
name: Lint project
on: push
jobs:
knip:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: npm install --ignore-scripts
- run: npm run knip -- --cache --reporter github-actions
- run: npm run knip -- --production --cachecli
knip CLI の基本実行・オプション別コマンド集。
基本実行
knipnpm run knippnpm knipbun knipバージョン・ヘルプ確認
knip --versionknip --helpBun ランタイムで実行
knip-bunカラー出力の無効化
NO_COLOR=1 knip環境変数 NO_COLOR を設定することでカラーなし出力になる。
プログレス表示の無効化
knip --no-progressCI 環境では自動的に適用される。
カスタム設定ファイルの指定
knip --config knip.custom.jsonknip -c knip.custom.jsontsconfig の指定
knip --tsConfig tsconfig.app.jsonknip -t tsconfig.app.jsontsconfig でプロジェクトファイルを定義
knip --use-tsconfig-files実行ディレクトリの変更
knip --directory packages/my-lib大規模コードベースでの表示制限
knip --max-show-issues 5最大 issue 数のしきい値設定(超過で exit 1)
knip --max-issues 10常に exit 0 で終了
knip --no-exit-code設定ヒントの非表示
knip --no-config-hints設定ヒントをエラーとして扱う
knip --treat-config-hints-as-errorsキャッシュを有効化(連続実行を 10-40% 高速化)
knip --cacheknip --cache --cache-location .cache/knipファイル変更の監視
knip --watchエントリーファイルの未使用 exports をレポートに含める
knip --include-entry-exports.gitignore を無視
knip --no-gitignoreカスタムレポーター形式
knip --reporter jsonknip --reporter markdownknip --reporter compactknip --reporter json --reporter-options '{"path":"knip-report.json"}'debug
knip のデバッグ・パフォーマンス分析・トレースコマンド集。
デバッグモードの有効化
knip --debug表示内容:
- 含まれるワークスペース一覧
- ワークスペースごとの設定
- 有効なプラグイン一覧
- glob パターンとマッチしたファイルパス
- プラグイン設定ファイルのパスと検出された依存関係
- コンパイルされた非標準ソースファイル
メモリ使用量の表示
knip --memoryknip --memory-realtimeパフォーマンス統計の表示
knip --performance単一関数のプロファイリング
knip --performance-fn <関数名>エクスポートの import 箇所のトレース
knip --trace特定ファイルのエクスポートトレース
knip --trace-file src/utils.ts正規表現パターンも使用可能。
特定エクスポート名のトレース
knip --trace-export myFunction特定パッケージ・バイナリ参照のトレース
knip --trace-dependency lodashワークスペースフィルタと組み合わせてトレース
knip --trace --workspace packages/my-libトレース凡例: ✓ (import あり) / x (import なし) / ◯ (エントリーファイル)
fix
knip の自動修正コマンド集。未使用コード・依存関係の自動除去。
自動修正の実行
警告:--fixはexportキーワードの除去・package.jsonの依存関係削除など不可逆な変更を加える。実行前に Git などの VCS でコミット済みであることを確認する。
knip --fix修正対象:
- 未使用 exports から
exportキーワードを除去 - 未使用 default exports から
export defaultを除去 - 未使用の enum / namespace メンバーを除去
package.jsonの未使用dependencies/devDependenciesを除去- 未使用の catalog エントリを除去
ファイル削除を許可して修正
警告: --allow-remove-files は未使用ファイルを削除する。VCS で管理済みであることを確認する。knip --fix --allow-remove-files修正後にフォーマッターを実行
knip --fix --formatBiome / deno fmt / dprint / Prettier を自動検出して実行する。
修正対象タイプを限定
knip --fix-type exports,typesknip --fix-type dependenciesknip --fix-type files--fix-type に指定できる値: dependencies, exports, types, files, catalog
ファイル削除 + フォーマット込み修正
警告: ファイルの削除と上書きを同時に行う。
knip --fix --allow-remove-files --formatinstall
knip のインストールとプロジェクトへのセットアップ。
自動セットアップ(推奨)
npm init @knip/configpnpm create @knip/configbun create @knip/configyarn create @knip/config設定ファイルと package.json スクリプトを自動生成する。
手動インストール
npm install -D knip typescript @types/nodetypescript と @types/node はピア依存関係。互換性向上のために同時インストールを推奨する。
package.json に以下を追加する:
{
"scripts": {
"knip": "knip"
}
}インストールなしで実行
npx knippnpm dlx knipbunx knip動作要件
- Node.js v20.19.0 以上、または Bun
lint
knip による未使用コード・依存関係・ファイルの検出コマンド集。
標準実行
knipexit code: 0 (issue なし) / 1 (issue あり) / 2 (例外)
issue タイプ別フィルタリング
knip --include filesknip --include dependenciesknip --include files,dependenciesknip --include files --exclude enumMembers,duplicatesissue タイプのショートカット
knip --filesknip --dependenciesknip --exportsタグフィルタリング
knip --tags=-lintignore,-internal+ で含める、- で除外する。JSDoc/TSDoc タグによるフィルタリング。
本番モード(本番ソースのみを解析)
knip --productionストリクトモード(ワークスペース分離 + 本番モード)
knip --production --strict本番モードで型 issue を除外
knip --production --exclude typesワークスペース指定
knip --workspace packages/my-libknip -W @myorg/my-libknip --workspace @myorg/* --workspace '!@myorg/legacy'knip --workspace './apps/*' --workspace '@shared/utils'issue タイプ一覧
files, dependencies, devDependencies, optionalPeerDependencies, unlisted, binaries, unresolved, exports, nsExports, types, nsTypes, enumMembers, namespaceMembers, duplicates, catalog
scripts
| Name | Description | Path |
|---|---|---|
| cli | knip CLI の基本実行・オプション別コマンド集。 | cli.md |
| ci | CI 環境での knip 実行コマンドと GitHub Actions 設定例。 | ci.md |
| debug | knip のデバッグ・パフォーマンス分析・トレースコマンド集。 | debug.md |
| fix | knip の自動修正コマンド集。未使用コード・依存関係の自動除去。 | fix.md |
| install | knip のインストールとプロジェクトへのセットアップ。 | install.md |
| lint | knip による未使用コード・依存関係・ファイルの検出コマンド集。 | lint.md |