knip-dead-code

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Knip Dead Code Detection

Knip 死代码检测

Knip is a comprehensive tool for finding unused code, dependencies, and exports in JavaScript and TypeScript projects. It helps maintain clean codebases and catch dead code before it accumulates.
Knip 是一款全面的工具,可用于在 JavaScript 和 TypeScript 项目中查找未使用的代码、依赖项及导出内容。它有助于维护整洁的代码库,并在死代码堆积前及时发现。

When to Use This Skill

适用场景

Use this skill when...Use another approach when...
Finding unused dependenciesRemoving unused CSS (use PurgeCSS)
Detecting unused exports in librariesFinding runtime dead code paths
Cleaning up codebases after refactorsOptimizing bundle size (use bundler tree-shaking)
Enforcing dependency hygiene in CIDetecting duplicate dependencies (use npm-dedupe)
适合使用该工具的场景...适合其他方案的场景...
查找未使用的依赖项移除未使用的CSS(使用PurgeCSS)
检测库中的未使用导出内容查找运行时死代码路径
重构后清理代码库优化包体积(使用打包器的摇树优化)
在CI中管控依赖项规范检测重复依赖项(使用npm-dedupe)

Core Expertise

核心功能

What is Knip?
  • Unused detection: Files, dependencies, exports, types, enum members
  • Plugin system: Supports 80+ frameworks and tools
  • Fast: Analyzes large codebases in seconds
  • Actionable: Clear reports with file locations
  • CI-ready: Exit codes for failing builds
什么是Knip?
  • 未使用内容检测:文件、依赖项、导出内容、类型、枚举成员
  • 插件系统:支持80+框架与工具
  • 快速分析:数秒内完成大型代码库的分析
  • 结果清晰:附带文件位置的明确报告
  • CI兼容:提供用于构建失败的退出码

Installation

安装

bash
undefined
bash
undefined

Project-local (recommended)

项目本地安装(推荐)

bun add --dev knip
bun add --dev knip

Verify installation

验证安装

bunx knip --version
undefined
bunx knip --version
undefined

Basic Usage

基础用法

bash
undefined
bash
undefined

Run Knip (scans entire project)

运行Knip(扫描整个项目)

bunx knip
bunx knip

Show only unused dependencies

仅显示未使用的依赖项

bunx knip --dependencies
bunx knip --dependencies

Show only unused exports

仅显示未使用的导出内容

bunx knip --exports
bunx knip --exports

Show only unused files

仅显示未使用的文件

bunx knip --files
bunx knip --files

Production mode (only check production dependencies)

生产模式(仅检查生产依赖项)

bunx knip --production
bunx knip --production

Exclude specific issue types

排除特定类型的问题

bunx knip --exclude-exports-used-in-file
bunx knip --exclude-exports-used-in-file

Output JSON (for CI)

输出JSON格式结果(用于CI)

bunx knip --reporter json
bunx knip --reporter json

Debug mode (show configuration)

调试模式(显示配置信息)

bunx knip --debug
undefined
bunx knip --debug
undefined

Configuration

配置

Auto-detection (Zero Config)

自动检测(零配置)

Knip automatically detects:
  • Entry points (package.json
    main
    ,
    exports
    ,
    bin
    )
  • Frameworks (Next.js, Vite, Remix, etc.)
  • Test runners (Vitest, Jest, Playwright)
  • Build tools (ESLint, TypeScript, PostCSS)
No configuration needed for standard projects.
Knip可自动检测:
  • 入口文件(package.json中的
    main
    exports
    bin
  • 框架(Next.js、Vite、Remix等)
  • 测试运行器(Vitest、Jest、Playwright)
  • 构建工具(ESLint、TypeScript、PostCSS)
标准项目无需额外配置。

knip.json (Explicit Configuration)

knip.json(显式配置)

json
{
  "$schema": "https://unpkg.com/knip@latest/schema.json",
  "entry": ["src/index.ts", "src/cli.ts"],
  "project": ["src/**/*.ts"],
  "ignore": ["**/*.test.ts", "scripts/**"],
  "ignoreDependencies": ["@types/*"],
  "ignoreBinaries": ["npm-check-updates"]
}
json
{
  "$schema": "https://unpkg.com/knip@latest/schema.json",
  "entry": ["src/index.ts", "src/cli.ts"],
  "project": ["src/**/*.ts"],
  "ignore": ["**/*.test.ts", "scripts/**"],
  "ignoreDependencies": ["@types/*"],
  "ignoreBinaries": ["npm-check-updates"]
}

knip.ts (TypeScript Configuration)

knip.ts(TypeScript配置)

typescript
// knip.ts
import type { KnipConfig } from 'knip';

const config: KnipConfig = {
  entry: ['src/index.ts', 'src/cli.ts'],
  project: ['src/**/*.ts', 'scripts/**/*.ts'],
  ignore: ['**/*.test.ts', '**/*.spec.ts', 'tmp/**'],
  ignoreDependencies: [
    '@types/*', // Type definitions
    'typescript', // Always needed
  ],
  ignoreExportsUsedInFile: true,
  ignoreWorkspaces: ['packages/legacy/**'],
};

export default config;
typescript
// knip.ts
import type { KnipConfig } from 'knip';

const config: KnipConfig = {
  entry: ['src/index.ts', 'src/cli.ts'],
  project: ['src/**/*.ts', 'scripts/**/*.ts'],
  ignore: ['**/*.test.ts', '**/*.spec.ts', 'tmp/**'],
  ignoreDependencies: [
    '@types/*', // 类型定义
    'typescript', // 始终需要
  ],
  ignoreExportsUsedInFile: true,
  ignoreWorkspaces: ['packages/legacy/**'],
};

export default config;

Common Patterns

常见使用模式

Check Only Unused Dependencies

仅检查未使用的依赖项

bash
undefined
bash
undefined

Fastest check - only dependencies

最快的检查方式 - 仅检查依赖项

bunx knip --dependencies
bunx knip --dependencies

Exit with error if any unused dependencies

若存在未使用依赖项则以错误码退出

bunx knip --dependencies --max-issues 0

**Use in CI to enforce strict dependency hygiene.**
bunx knip --dependencies --max-issues 0

**用于CI环境以严格管控依赖项规范。**

Check Only Exports (Library Development)

仅检查导出内容(库开发场景)

bash
undefined
bash
undefined

Check for unused exports

检查未使用的导出内容

bunx knip --exports
bunx knip --exports

Allow exports used in same file

允许在同一文件中使用的导出内容

bunx knip --exports --exclude-exports-used-in-file

**Use for libraries to ensure clean public API.**
bunx knip --exports --exclude-exports-used-in-file

**用于类库开发,确保公共API的整洁性。**

Production vs Development Dependencies

生产依赖与开发依赖

bash
undefined
bash
undefined

Check production code only

仅检查生产代码

bunx knip --production
bunx knip --production

Check everything (including dev dependencies)

检查全部内容(包括开发依赖)

bunx knip
undefined
bunx knip
undefined

Interpreting Results

结果解读

Example Output

输出示例

No unused files
No unused dependencies
2 unused exports

src/utils.ts:
  - calculateTax (line 42)
  - formatDate (line 58)

src/types.ts:
  - UserRole (line 12)
No unused files
No unused dependencies
2 unused exports

src/utils.ts:
  - calculateTax (line 42)
  - formatDate (line 58)

src/types.ts:
  - UserRole (line 12)

Issue Types

问题类型

TypeDescriptionAction
Unused fileFile not imported anywhereDelete or add to entry points
Unused dependencyPackage in package.json not usedRemove from dependencies
Unused exportExported but never importedRemove export or make private
Unused typeType/interface exported but unusedRemove or make internal
Unused enum memberEnum member never referencedRemove member
Duplicate exportSame export from multiple filesConsolidate exports
类型描述处理建议
未使用文件文件未被任何地方引入删除该文件或添加至入口点
未使用依赖项package.json中的包未被使用从依赖项中移除
未使用导出内容已导出但从未被引入删除导出或将其设为私有
未使用类型已导出的类型/接口未被使用删除或设为内部使用
未使用枚举成员枚举成员从未被引用删除该成员
重复导出同一内容从多个文件导出整合导出逻辑

Agentic Optimizations

智能化优化场景

ContextCommand
Quick scan
bunx knip
Dependencies only
bunx knip --dependencies
Exports only
bunx knip --exports
CI strict mode
bunx knip --max-issues 0
Production check
bunx knip --production
JSON output
bunx knip --reporter json
Debug config
bunx knip --debug
Changed files
bunx knip --changed --base main
场景命令
快速扫描
bunx knip
仅检查依赖项
bunx knip --dependencies
仅检查导出内容
bunx knip --exports
CI严格模式
bunx knip --max-issues 0
生产环境检查
bunx knip --production
JSON格式输出
bunx knip --reporter json
调试配置
bunx knip --debug
仅检查变更文件
bunx knip --changed --base main

Quick Reference

快速参考

FlagDescription
--dependencies
Check only unused dependencies
--exports
Check only unused exports
--files
Check only unused files
--production
Production dependencies only
--max-issues N
Fail if more than N issues
--reporter json
JSON output for CI
--reporter compact
Compact output
--debug
Show configuration details
--changed
Check only changed files
--changed --base main
Changed files since main
--workspace NAME
Check specific workspace
--exclude-exports-used-in-file
Ignore same-file exports
For detailed examples, advanced patterns, and best practices, see REFERENCE.md.
参数描述
--dependencies
仅检查未使用的依赖项
--exports
仅检查未使用的导出内容
--files
仅检查未使用的文件
--production
仅检查生产依赖项
--max-issues N
若问题数超过N则失败
--reporter json
输出JSON格式结果用于CI
--reporter compact
输出精简格式结果
--debug
显示配置详情
--changed
仅检查变更的文件
--changed --base main
检查自main分支以来变更的文件
--workspace NAME
检查指定的工作区
--exclude-exports-used-in-file
忽略同一文件内使用的导出内容
如需查看详细示例、高级用法及最佳实践,请参阅 REFERENCE.md

References

参考链接