fallow

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Fallow: codebase intelligence for JavaScript and TypeScript

Fallow:面向JavaScript和TypeScript的代码库智能分析工具

Codebase intelligence for JavaScript and TypeScript. The free static layer finds unused code, circular dependencies, code duplication, complexity hotspots, architecture boundary violations, and feature flag patterns. The optional paid runtime layer (Fallow Runtime) merges production execution data into the same
fallow health
report for hot-path review, cold-path deletion confidence, and stale-flag evidence. 90 framework plugins, zero configuration, sub-second static analysis.
面向JavaScript和TypeScript的代码库智能分析工具。免费静态分析层可检测未使用代码、循环依赖、代码重复、复杂度热点、架构边界违规以及特性标记模式。可选付费运行时层(Fallow Runtime)可将生产环境执行数据整合到同一份
fallow health
报告中,用于热路径审查、冷路径删除确认以及过期标记验证。支持90种框架插件,零配置,静态分析耗时不到一秒。

When to Use

使用场景

  • Finding dead code (unused files, exports, types, enum/class members)
  • Finding unused or unlisted dependencies
  • Detecting code duplication and clones
  • Checking code health and complexity hotspots
  • Cleaning up a codebase before a release or refactor
  • Auditing a project for structural issues
  • Setting up CI checks for dead code or duplication thresholds
  • Auto-fixing unused exports and dependencies
  • Detecting feature flag patterns (environment gates, SDK calls, config objects)
  • Investigating why a specific export or file appears unused
  • 查找死代码(未使用的文件、导出项、类型、枚举/类成员)
  • 查找未使用或未声明的依赖
  • 检测代码重复与克隆
  • 检查代码健康度与复杂度热点
  • 发布或重构前清理代码库
  • 审计项目的结构性问题
  • 为死代码或重复代码阈值设置CI检查
  • 自动修复未使用的导出项与依赖
  • 检测特性标记模式(环境网关、SDK调用、配置对象)
  • 排查特定导出项或文件显示未使用的原因

When NOT to Use

非适用场景

  • Runtime error analysis or debugging
  • Type checking (use
    tsc
    for that)
  • Linting style or formatting issues (use ESLint, Biome, Prettier)
  • Security vulnerability scanning
  • Bundle size analysis
  • Projects that are not JavaScript or TypeScript
  • 运行时错误分析或调试
  • 类型检查(请使用
    tsc
  • 代码风格或格式检查(请使用ESLint、Biome、Prettier)
  • 安全漏洞扫描
  • 包体积分析
  • 非JavaScript/TypeScript项目

Prerequisites

前置条件

Fallow must be installed. If not available, install it:
bash
npm install -g fallow          # prebuilt binaries (fastest)
必须安装Fallow。若未安装,可执行以下命令:
bash
npm install -g fallow          # 预构建二进制包(速度最快)

or

npx fallow dead-code # run without installing
npx fallow dead-code # 无需安装直接运行

or

cargo install fallow-cli # build from source
undefined
cargo install fallow-cli # 从源码构建
undefined

Agent Rules

Agent规则

  1. Always use
    --format json --quiet 2>/dev/null
    for machine-readable output. The
    2>/dev/null
    discards stderr so progress messages and threshold warnings don't corrupt the JSON on stdout. Never use
    2>&1
  2. Always append
    || true
    to every fallow command. Exit code 1 means "issues found" (normal), not a runtime error. Without
    || true
    , the Bash tool treats exit 1 as failure and cancels parallel commands. Only exit code 2 is a real error (invalid config, parse failure)
  3. Use
    --explain
    to include a
    _meta
    object in JSON output with metric definitions, ranges, and interpretation hints
  4. Use issue type filters (
    --unused-exports
    ,
    --unused-files
    , etc.) to limit output scope
  5. Always
    --dry-run
    before
    fix
    , then
    fix --yes
    to apply
  6. All output paths are relative to the project root
  7. Never run
    fallow watch
    . It is interactive and never exits
  1. **始终使用
    --format json --quiet 2>/dev/null
    **以获取机器可读的输出。
    2>/dev/null
    用于丢弃stderr输出,避免进度消息和阈值警告破坏stdout中的JSON格式。请勿使用
    2>&1
  2. 始终在每个fallow命令后追加
    || true
    。退出码1表示“发现问题”(正常情况),而非运行时错误。如果不添加
    || true
    ,Bash工具会将退出码1视为失败,并取消并行命令。只有退出码2才代表真正的错误(无效配置、解析失败)
  3. **使用
    --explain
    **以在JSON输出中包含带有指标定义、范围和解释提示的
    _meta
    对象
  4. 使用问题类型过滤器
    --unused-exports
    --unused-files
    等)限制输出范围
  5. **执行
    fix
    前务必先
    --dry-run
    **确认,然后使用
    fix --yes
    应用修复
  6. 所有输出路径均相对于项目根目录
  7. 切勿运行
    fallow watch
    。该命令为交互式,不会自动退出

Commands

命令列表

CommandPurposeKey Flags
fallow
Run all analyses: dead code + duplication + complexity (default)
--only
,
--skip
,
--ci
,
--fail-on-issues
,
--group-by
,
--summary
,
--fail-on-regression
,
--tolerance
,
--regression-baseline
,
--save-regression-baseline
,
--score
,
--trend
,
--save-snapshot
dead-code
Dead code analysis (
check
is an alias)
--unused-exports
,
--changed-since
,
--changed-workspaces
,
--production
,
--file
,
--include-entry-exports
,
--stale-suppressions
,
--ci
,
--group-by
,
--summary
,
--fail-on-regression
,
--tolerance
,
--regression-baseline
,
--save-regression-baseline
dupes
Code duplication detection
--mode
,
--threshold
,
--top
,
--changed-since
,
--workspace
,
--changed-workspaces
,
--skip-local
,
--cross-language
,
--ignore-imports
,
--fail-on-regression
,
--tolerance
,
--regression-baseline
,
--save-regression-baseline
fix
Auto-remove unused exports/deps
--dry-run
,
--yes
(required in non-TTY)
init
Generate config file or pre-commit hook
--toml
,
--hooks
,
--branch
migrate
Convert knip/jscpd config
--dry-run
,
--from PATH
list
Inspect project structure
--files
,
--entry-points
,
--plugins
,
--boundaries
health
Function complexity analysis
--complexity
,
--max-cyclomatic
,
--max-cognitive
,
--max-crap
,
--top
,
--sort
,
--file-scores
,
--hotspots
,
--ownership
,
--ownership-emails
,
--targets
,
--effort
,
--score
,
--min-score
,
--since
,
--min-commits
,
--save-snapshot
,
--trend
,
--coverage-gaps
,
--coverage
,
--coverage-root
,
--production-coverage
,
--min-invocations-hot
,
--min-observation-volume
,
--low-traffic-threshold
,
--workspace
,
--changed-workspaces
,
--baseline
,
--save-baseline
audit
Combined dead-code + complexity + duplication for changed files
--base
,
--production
,
--workspace
,
--changed-workspaces
,
--ci
,
--fail-on-issues
,
--explain
,
--dead-code-baseline
,
--health-baseline
,
--dupes-baseline
,
--max-crap
flags
Detect feature flag patterns (env vars, SDK calls, config objects)
--top
license
Manage the local license JWT for paid features (activate, status, refresh, deactivate)
activate --trial --email <addr>
,
activate --from-file
,
activate --stdin
,
status
,
refresh
,
deactivate
coverage
Production-coverage workflow helper (paid)
setup
,
setup --yes
,
setup --non-interactive
schema
Dump CLI definition as JSON
config
Show the loaded config path and resolved config (verifies which
.fallowrc.json
is in effect)
--path
命令用途关键参数
fallow
运行所有分析:死代码+重复代码+复杂度(默认)
--only
,
--skip
,
--ci
,
--fail-on-issues
,
--group-by
,
--summary
,
--fail-on-regression
,
--tolerance
,
--regression-baseline
,
--save-regression-baseline
,
--score
,
--trend
,
--save-snapshot
dead-code
死代码分析(
check
为别名)
--unused-exports
,
--changed-since
,
--changed-workspaces
,
--production
,
--file
,
--include-entry-exports
,
--stale-suppressions
,
--ci
,
--group-by
,
--summary
,
--fail-on-regression
,
--tolerance
,
--regression-baseline
,
--save-regression-baseline
dupes
代码重复检测
--mode
,
--threshold
,
--top
,
--changed-since
,
--workspace
,
--changed-workspaces
,
--skip-local
,
--cross-language
,
--ignore-imports
,
--fail-on-regression
,
--tolerance
,
--regression-baseline
,
--save-regression-baseline
fix
自动移除未使用的导出项/依赖
--dry-run
,
--yes
(非TTY环境必填)
init
生成配置文件或预提交钩子
--toml
,
--hooks
,
--branch
migrate
转换knip/jscpd配置
--dry-run
,
--from PATH
list
查看项目结构
--files
,
--entry-points
,
--plugins
,
--boundaries
health
函数复杂度分析
--complexity
,
--max-cyclomatic
,
--max-cognitive
,
--max-crap
,
--top
,
--sort
,
--file-scores
,
--hotspots
,
--ownership
,
--ownership-emails
,
--targets
,
--effort
,
--score
,
--min-score
,
--since
,
--min-commits
,
--save-snapshot
,
--trend
,
--coverage-gaps
,
--coverage
,
--coverage-root
,
--production-coverage
,
--min-invocations-hot
,
--min-observation-volume
,
--low-traffic-threshold
,
--workspace
,
--changed-workspaces
,
--baseline
,
--save-baseline
audit
针对变更文件的死代码+复杂度+重复代码综合分析
--base
,
--production
,
--workspace
,
--changed-workspaces
,
--ci
,
--fail-on-issues
,
--explain
,
--dead-code-baseline
,
--health-baseline
,
--dupes-baseline
,
--max-crap
flags
检测特性标记模式(环境变量、SDK调用、配置对象)
--top
license
管理付费功能的本地许可证JWT(激活、状态查询、刷新、停用)
activate --trial --email <addr>
,
activate --from-file
,
activate --stdin
,
status
,
refresh
,
deactivate
coverage
生产环境覆盖率工作流辅助工具(付费)
setup
,
setup --yes
,
setup --non-interactive
schema
将CLI定义导出为JSON格式
config
显示加载的配置文件路径和解析后的配置(验证当前生效的
.fallowrc.json
--path

Issue Types

问题类型

TypeFilter FlagDescription
Unused files
--unused-files
Files unreachable from entry points
Unused exports
--unused-exports
Symbols never imported elsewhere
Unused types
--unused-types
Type aliases and interfaces
Unused dependencies
--unused-deps
Packages in
dependencies
,
devDependencies
,
optionalDependencies
, type-only production deps, and test-only production deps
Unused enum members
--unused-enum-members
Enum values never referenced
Unused class members
--unused-class-members
Methods and properties
Unresolved imports
--unresolved-imports
Imports that can't be resolved
Unlisted dependencies
--unlisted-deps
Used packages missing from package.json
Duplicate exports
--duplicate-exports
Same symbol exported from multiple modules
Circular dependencies
--circular-deps
Import cycles in the module graph
Boundary violations
--boundary-violations
Imports crossing architecture zone boundaries. Presets:
layered
,
hexagonal
,
feature-sliced
,
bulletproof
Stale suppressions
--stale-suppressions
fallow-ignore
comments or
@expected-unused
JSDoc tags that no longer match any issue
Test-only dependenciesn/aProduction deps only imported from test files (should be devDependencies)
类型过滤参数描述
未使用文件
--unused-files
无法从入口点访问的文件
未使用导出项
--unused-exports
从未被其他地方导入的符号
未使用类型
--unused-types
类型别名和接口
未使用依赖
--unused-deps
dependencies
devDependencies
optionalDependencies
中的包,仅类型使用的生产依赖,以及仅测试使用的生产依赖
未使用枚举成员
--unused-enum-members
从未被引用的枚举值
未使用类成员
--unused-class-members
方法和属性
未解析导入
--unresolved-imports
无法解析的导入项
未声明依赖
--unlisted-deps
已使用但未在package.json中声明的包
重复导出项
--duplicate-exports
从多个模块导出的相同符号
循环依赖
--circular-deps
模块图中的导入循环
边界违规
--boundary-violations
跨越架构区域边界的导入。预设规则:
layered
hexagonal
feature-sliced
bulletproof
过期抑制规则
--stale-suppressions
fallow-ignore
注释或
@expected-unused
JSDoc标记不再匹配任何问题
仅测试依赖n/a仅从测试文件导入的生产依赖(应移至devDependencies)

MCP Tools

MCP工具

When using fallow via MCP (
fallow-mcp
), the following tools are available:
ToolDescription
analyze
Full dead code analysis. Set
boundary_violations: true
as a convenience alias for
issue_types: ["boundary-violations"]
. Set
group_by
to
"owner"
,
"directory"
,
"package"
, or
"section"
(GitLab CODEOWNERS
[Section]
headers, with
owners
metadata per group) to partition results
check_changed
Incremental analysis of files changed since a git ref
find_dupes
Code duplication detection. Set
changed_since
to scope to changed files since a git ref
fix_preview
Dry-run auto-fix preview
fix_apply
Apply auto-fixes (destructive)
check_health
Complexity metrics, health scores, hotspots, and refactoring targets
check_production_coverage
Merge V8 or Istanbul production-coverage data into the health report (paid). Required
coverage
param (V8 dir, V8 JSON, or Istanbul
coverage-final.json
). Tuning knobs:
min_invocations_hot
(default 100),
min_observation_volume
(default 5000),
low_traffic_threshold
(default 0.001),
max_crap
(default 30.0),
group_by
. Long dumps may exceed the 120s MCP timeout; raise
FALLOW_TIMEOUT_SECS
. Pick this over
check_health
when you have a coverage dump.
audit
Combined dead-code + complexity + duplication for changed files, returns verdict
project_info
Project metadata. Set
entry_points
,
files
,
plugins
, or
boundaries
to
true
to request specific sections
list_boundaries
Architecture boundary zones and access rules. Returns
{"configured": false}
if no boundaries configured
feature_flags
Detect feature flag patterns (env vars, SDK calls, config objects). Set
top
to limit results
trace_export
Trace why an export is used or unused (
fallow dead-code --trace FILE:EXPORT_NAME --format json
). Required
file
and
export_name
. Returns file reachability, entry-point status, direct references, re-export chains, and a reason string. Use before deleting a supposedly-unused export
trace_file
Trace all graph edges for a file (
fallow dead-code --trace-file PATH --format json
). Required
file
. Returns reachability, exports, imports-from, imported-by, and re-exports. Use to decide whether a file is isolated, barrel-only, or imported by live entry points
trace_dependency
Trace where a dependency is imported (
fallow dead-code --trace-dependency PACKAGE --format json
). Required
package_name
. Returns importing files, type-only importers, and total import count. Use before removing a dependency or moving between
dependencies
and
devDependencies
trace_clone
Trace duplicate-code groups at a location (
fallow dupes --trace FILE:LINE --format json
). Required
file
and
line
. Returns the matched clone instance plus every clone group containing it. Supports
mode
,
min_tokens
,
min_lines
,
threshold
,
skip_local
,
cross_language
,
ignore_imports
. Use to consolidate duplication when you need the exact sibling locations
All tools accept
root
,
config
,
no_cache
, and
threads
params. The MCP server subprocess timeout defaults to 120s, configurable via
FALLOW_TIMEOUT_SECS
.
All JSON responses include structured
actions
arrays on every finding (dead code, health, duplication), enabling programmatic fix application or suppression.
通过MCP(
fallow-mcp
)使用fallow时,可使用以下工具:
工具描述
analyze
完整的死代码分析。设置
boundary_violations: true
作为
issue_types: ["boundary-violations"]
的便捷别名。设置
group_by
"owner"
"directory"
"package"
"section"
(GitLab CODEOWNERS的
[Section]
标题,每组包含
owners
元数据)以划分结果
check_changed
针对Git基准版本以来变更文件的增量分析
find_dupes
代码重复检测。设置
changed_since
以限定为Git基准版本以来的变更文件
fix_preview
自动修复的预演(干运行)
fix_apply
应用自动修复(破坏性操作)
check_health
复杂度指标、健康评分、热点区域和重构目标分析
check_production_coverage
将V8或Istanbul生产环境覆盖率数据整合到健康报告中(付费)。必填
coverage
参数(V8目录、V8 JSON或Istanbul的
coverage-final.json
)。可调参数:
min_invocations_hot
(默认100)、
min_observation_volume
(默认5000)、
low_traffic_threshold
(默认0.001)、
max_crap
(默认30.0)、
group_by
。长输出可能超过120秒的MCP超时限制;可提高
FALLOW_TIMEOUT_SECS
。当您有覆盖率数据时,优先选择此工具而非
check_health
audit
针对变更文件的死代码+复杂度+重复代码综合分析,返回结论
project_info
项目元数据。设置
entry_points
files
plugins
boundaries
true
以请求特定部分的信息
list_boundaries
架构边界区域和访问规则。若未配置边界,则返回
{"configured": false}
feature_flags
检测特性标记模式(环境变量、SDK调用、配置对象)。设置
top
以限制结果数量
trace_export
追踪导出项被使用或未被使用的原因(
fallow dead-code --trace FILE:EXPORT_NAME --format json
)。必填
file
export_name
参数。返回文件可达性、入口点状态、直接引用、重导出链以及原因说明。删除疑似未使用的导出项前使用此工具
trace_file
追踪文件的所有图边(
fallow dead-code --trace-file PATH --format json
)。必填
file
参数。返回可达性、导出项、导入来源、被导入对象以及重导出信息。用于判断文件是否孤立、仅作为桶文件或被活跃入口点导入
trace_dependency
追踪依赖的导入位置(
fallow dead-code --trace-dependency PACKAGE --format json
)。必填
package_name
参数。返回导入该依赖的文件、仅类型导入的文件以及总导入次数。删除依赖或在
dependencies
devDependencies
之间移动依赖前使用此工具
trace_clone
追踪指定位置的重复代码组(
fallow dupes --trace FILE:LINE --format json
)。必填
file
line
参数。返回匹配的克隆实例以及包含该实例的所有克隆组。支持
mode
min_tokens
min_lines
threshold
skip_local
cross_language
ignore_imports
参数。需要精确的同级位置信息时,使用此工具整合重复代码
所有工具均接受
root
config
no_cache
threads
参数。MCP服务器子进程的默认超时时间为120秒,可通过
FALLOW_TIMEOUT_SECS
配置。
所有JSON响应的每个检测结果(死代码、健康度、重复代码)均包含结构化的
actions
数组,支持程序化应用修复或抑制规则。

Node.js Bindings

Node.js绑定

When embedding fallow inside a Node.js process (editor extensions, long-running servers, custom tooling), prefer the NAPI bindings over spawning the CLI. Same analysis engine, same JSON envelopes, no subprocess or JSON parsing overhead.
bash
npm install @fallow-cli/fallow-node
ts
import { detectDeadCode, detectDuplication, computeHealth } from '@fallow-cli/fallow-node';

const deadCode = await detectDeadCode({ root: process.cwd(), explain: true });
const dupes = await detectDuplication({ root: process.cwd(), mode: 'mild', minTokens: 30 });
const health = await computeHealth({ root: process.cwd(), score: true, ownershipEmails: 'handle' });
Six async functions:
detectDeadCode
,
detectCircularDependencies
,
detectBoundaryViolations
,
detectDuplication
,
computeComplexity
,
computeHealth
. Each returns the same JSON envelope the CLI emits for
--format json
. Rejected promises throw a
FallowNodeError
with
message
,
exitCode
, and optional
code
,
help
,
context
fields that mirror the CLI's structured error surface.
Enum-like fields take lowercase CLI-style literals (
"mild"
,
"cyclomatic"
,
"handle"
,
"low"
). Write-path commands (
fix
,
init
,
setup-hooks
,
license activate
,
coverage setup
) are not exposed; use the CLI for those.
将fallow嵌入Node.js进程(编辑器扩展、长期运行的服务器、自定义工具)时,优先使用NAPI绑定而非调用CLI。使用相同的分析引擎和JSON格式,无进程开销或JSON解析开销。
bash
npm install @fallow-cli/fallow-node
ts
import { detectDeadCode, detectDuplication, computeHealth } from '@fallow-cli/fallow-node';

const deadCode = await detectDeadCode({ root: process.cwd(), explain: true });
const dupes = await detectDuplication({ root: process.cwd(), mode: 'mild', minTokens: 30 });
const health = await computeHealth({ root: process.cwd(), score: true, ownershipEmails: 'handle' });
提供六个异步函数:
detectDeadCode
detectCircularDependencies
detectBoundaryViolations
detectDuplication
computeComplexity
computeHealth
。每个函数返回与CLI
--format json
输出相同的JSON格式。 Promise拒绝时会抛出
FallowNodeError
,包含
message
exitCode
以及可选的
code
help
context
字段,与CLI的结构化错误输出一致。
枚举类字段接受小写的CLI风格字面量(
"mild"
"cyclomatic"
"handle"
"low"
)。写入类命令(
fix
init
setup-hooks
license activate
coverage setup
)未对外暴露;请使用CLI执行这些操作。

References

参考文档

  • CLI Reference: complete command and flag specifications
  • Gotchas: common pitfalls, edge cases, and correct usage patterns
  • Patterns: workflow recipes for CI, monorepos, migration, and incremental adoption
  • CLI参考文档:完整的命令和参数说明
  • 常见陷阱:常见误区、边缘情况和正确使用模式
  • 工作流模式:CI、单体仓库、迁移和增量采用的工作流方案

Common Workflows

常见工作流

Audit a project for all dead code

审计项目中的所有死代码

bash
fallow dead-code --format json --quiet
Parse the JSON output. It contains arrays for each issue type (
unused_files
,
unused_exports
,
unused_types
,
unused_dependencies
, etc.) plus
total_issues
and
elapsed_ms
metadata. Each issue object includes an
actions
array with structured fix suggestions (action type,
auto_fixable
flag, description, and optional suppression comment).
bash
fallow dead-code --format json --quiet
解析JSON输出。输出包含每种问题类型的数组(
unused_files
unused_exports
unused_types
unused_dependencies
等),以及
total_issues
elapsed_ms
元数据。每个问题对象包含
actions
数组,其中包含结构化的修复建议(操作类型、
auto_fixable
标记、描述以及可选的抑制注释)。

Find only unused exports (smaller output)

仅查找未使用的导出项(输出更简洁)

bash
fallow dead-code --format json --quiet --unused-exports
bash
fallow dead-code --format json --quiet --unused-exports

Check if a PR introduces dead code

检查PR是否引入死代码

bash
fallow dead-code --format json --quiet --changed-since main --fail-on-issues
Exit code 1 if new dead code is introduced. Only analyzes files changed since the
main
branch.
bash
fallow dead-code --format json --quiet --changed-since main --fail-on-issues
如果引入新的死代码,退出码为1。仅分析
main
分支以来变更的文件。

Find code duplication

查找代码重复

bash
fallow dupes --format json --quiet
fallow dupes --format json --quiet --mode semantic
The
semantic
mode detects renamed variables. Other modes:
strict
(exact),
mild
(default, syntax normalized),
weak
(different literals).
bash
fallow dupes --format json --quiet
fallow dupes --format json --quiet --mode semantic
semantic
模式可检测重命名的变量。其他模式:
strict
(完全匹配)、
mild
(默认,语法标准化)、
weak
(忽略字面量差异)。

Safe auto-fix cycle

安全的自动修复流程

bash
undefined
bash
undefined

1. Preview what will be removed

1. 预览将被移除的内容

fallow fix --dry-run --format json --quiet
fallow fix --dry-run --format json --quiet

2. Review the output, then apply

2. 查看输出后,应用修复

fallow fix --yes --format json --quiet
fallow fix --yes --format json --quiet

3. Verify the fix worked

3. 验证修复效果

fallow dead-code --format json --quiet

The `--yes` flag is required in non-TTY environments (agent subprocesses). Without it, `fix` exits with code 2.
fallow dead-code --format json --quiet

非TTY环境(Agent子进程)中必须使用`--yes`参数。否则`fix`命令会以退出码2终止。

Discover project structure

查看项目结构

bash
fallow list --entry-points --format json --quiet
fallow list --plugins --format json --quiet
Shows detected entry points and active framework plugins (91 built-in: Next.js, Vite, Jest, Storybook, Tailwind, PandaCSS, etc.).
bash
fallow list --entry-points --format json --quiet
fallow list --plugins --format json --quiet
显示检测到的入口点和激活的框架插件(内置91种:Next.js、Vite、Jest、Storybook、Tailwind、PandaCSS等)。

Production-only analysis

仅生产环境分析

bash
fallow dead-code --format json --quiet --production
Excludes test/dev files (
*.test.*
,
*.spec.*
,
*.stories.*
) and only analyzes production scripts.
bash
fallow dead-code --format json --quiet --production
排除测试/开发文件(
*.test.*
*.spec.*
*.stories.*
),仅分析生产脚本。

Analyze specific workspaces

分析特定工作区

bash
undefined
bash
undefined

Single package

单个包

fallow dead-code --format json --quiet --workspace my-package
fallow dead-code --format json --quiet --workspace my-package

Multiple packages

多个包

fallow dead-code --format json --quiet --workspace web,admin
fallow dead-code --format json --quiet --workspace web,admin

Glob (matched against package name AND workspace path)

通配符(匹配包名称和工作区路径)

fallow dead-code --format json --quiet --workspace 'apps/*'
fallow dead-code --format json --quiet --workspace 'apps/*'

Exclude one workspace from a set

从集合中排除一个工作区

fallow dead-code --format json --quiet --workspace 'apps/*,!apps/legacy'
fallow dead-code --format json --quiet --workspace 'apps/*,!apps/legacy'

Monorepo CI: auto-scope to workspaces containing any file changed since origin/main

单体仓库CI:自动限定为origin/main以来有文件变更的工作区

(replaces hand-written --workspace lists that drift as the repo evolves)

(替代手写的--workspace列表,避免仓库演进时列表失效)

fallow dead-code --format json --quiet --changed-workspaces origin/main

Scopes output while keeping the full cross-workspace graph. Patterns are tested against BOTH the package name (from `package.json`) AND the workspace path relative to the repo root; either match counts. Use `!`-prefixed patterns to exclude.

`--changed-workspaces <REF>` auto-derives the set from `git diff`. It's the CI primitive: point it at the PR base branch (e.g. `origin/main`) and fallow reports only on workspaces touched by the change. Mutually exclusive with `--workspace`. A missing ref or non-git directory is a hard error (exit 2) rather than a silent full-scope fallback, so CI never quietly widens back to the whole monorepo.
fallow dead-code --format json --quiet --changed-workspaces origin/main

在保持完整跨工作区图的同时限定输出范围。模式会同时匹配包名称(来自`package.json`)和相对于仓库根目录的工作区路径;任一匹配即可。使用`!`前缀的模式进行排除。

`--changed-workspaces <REF>`通过`git diff`自动推导工作区集合。这是CI的核心功能:将其指向PR的基准分支(如`origin/main`),fallow仅报告变更涉及的工作区。该参数与`--workspace`互斥。如果基准分支不存在或目录不是Git仓库,会触发严重错误(退出码2),而非静默回退到全范围分析,确保CI不会意外扩大分析范围到整个单体仓库。

Scope to specific files (lint-staged)

限定为特定文件(lint-staged)

bash
fallow dead-code --format json --quiet --file src/utils.ts --file src/helpers.ts
Only reports issues in the specified files. Project-wide dependency issues are suppressed. Warns on non-existent paths.
bash
fallow dead-code --format json --quiet --file src/utils.ts --file src/helpers.ts
仅报告指定文件中的问题。项目级依赖问题会被抑制。路径不存在时会发出警告。

Catch typos in entry file exports

捕获入口文件导出项中的拼写错误

bash
fallow dead-code --format json --quiet --include-entry-exports
Reports unused exports in entry files (package.json
main
/
exports
, framework pages). By default, exports in entry files are assumed externally consumed. This flag catches typos like
meatdata
instead of
metadata
.
bash
fallow dead-code --format json --quiet --include-entry-exports
报告入口文件(package.json的
main
/
exports
、框架页面)中的未使用导出项。默认情况下,入口文件中的导出项被视为外部使用。此参数可捕获类似
meatdata
而非
metadata
的拼写错误。

Debug why something is flagged

调试标记问题的原因

bash
undefined
bash
undefined

Trace an export's usage chain

追踪导出项的使用链

fallow dead-code --format json --quiet --trace src/utils.ts:myFunction
fallow dead-code --format json --quiet --trace src/utils.ts:myFunction

Trace all edges for a file

追踪文件的所有关联

fallow dead-code --format json --quiet --trace-file src/utils.ts
fallow dead-code --format json --quiet --trace-file src/utils.ts

Trace where a dependency is used

追踪依赖的使用位置

fallow dead-code --format json --quiet --trace-dependency lodash
undefined
fallow dead-code --format json --quiet --trace-dependency lodash
undefined

Migrate from knip or jscpd

从knip或jscpd迁移

bash
undefined
bash
undefined

Preview migration

预览迁移

fallow migrate --dry-run
fallow migrate --dry-run

Apply migration (creates .fallowrc.json)

应用迁移(创建.fallowrc.json)

fallow migrate
fallow migrate

Migrate to TOML (creates fallow.toml)

迁移到TOML格式(创建fallow.toml)

fallow migrate --toml

Auto-detects `knip.json`, `.knip.json`, `.jscpd.json`, and package.json embedded configs.
fallow migrate --toml

自动检测`knip.json`、`.knip.json`、`.jscpd.json`以及package.json中的嵌入式配置。

Initialize a new config

初始化新配置

bash
fallow init              # creates .fallowrc.json, adds .fallow/ to .gitignore
fallow init --toml       # creates fallow.toml, adds .fallow/ to .gitignore
fallow init --hooks      # scaffold a pre-commit git hook
fallow init --hooks --branch develop  # hook using custom base branch
bash
fallow init              # 创建.fallowrc.json,将.fallow/添加到.gitignore
fallow init --toml       # 创建fallow.toml,将.fallow/添加到.gitignore
fallow init --hooks      # 生成预提交Git钩子
fallow init --hooks --branch develop  # 使用自定义基准分支的钩子

Exit Codes

退出码

CodeMeaning
0Success, no error-severity issues
1Error-severity issues found
2Runtime error (invalid config, parse failure, or
fix
without
--yes
in non-TTY)
When
--format json
is active and exit code is 2, errors are emitted as JSON on stdout:
json
{"error": true, "message": "invalid config: ...", "exit_code": 2}
代码含义
0成功,未发现错误级问题
1发现错误级问题
2运行时错误(无效配置、解析失败,或非TTY环境中执行
fix
未加
--yes
--format json
启用且退出码为2时,错误信息会以JSON格式输出到stdout:
json
{"error": true, "message": "invalid config: ...", "exit_code": 2}

Configuration

配置

Fallow reads config from project root:
.fallowrc.json
>
fallow.toml
>
.fallow.toml
. Most projects work with zero configuration thanks to 90 auto-detecting framework plugins.
jsonc
{
  "$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json",
  "entry": ["src/index.ts"],
  "ignorePatterns": ["**/*.generated.ts"],
  "ignoreDependencies": ["autoprefixer"],
  "publicPackages": ["@myorg/shared-lib"],
  "dynamicallyLoaded": ["plugins/**/*.ts"],
  "rules": {
    "unused-files": "error",
    "unused-exports": "warn",
    "unused-types": "off"
  }
}
Rules:
"error"
(fail CI),
"warn"
(report only),
"off"
(skip detection).
Config fields:
  • publicPackages
    : workspace packages that are public libraries; exports from these packages are not flagged as unused
  • dynamicallyLoaded
    : glob patterns for files loaded at runtime (plugin dirs, locale files); treated as always-used
  • usedClassMembers
    : class method/property names that extend the built-in Angular/React lifecycle allowlist with framework-invoked names. Each entry is a plain string (global suppression) or a scoped object
    { extends?, implements?, members }
    matching only classes with the given heritage. Use scoped rules for common names like
    refresh
    or
    execute
    to avoid false negatives on unrelated classes; global strings for unique names like
    agInit
    . Example:
    ["agInit", { "implements": "ICellRendererAngularComp", "members": ["refresh"] }, { "extends": "BaseCommand", "members": ["execute"] }]
    . An unconstrained scoped rule (no
    extends
    or
    implements
    ) is rejected at load time. Use plugin-level
    usedClassMembers
    in a
    .fallow/plugins/*.jsonc
    file for library-specific allowlists
  • resolve.conditions
    : additional package.json
    exports
    /
    imports
    condition names to honor during module resolution. Baseline conditions (
    development
    ,
    import
    ,
    require
    ,
    default
    ,
    types
    ,
    node
    , plus
    react-native
    /
    browser
    under RN/Expo) are always included; user entries prepend ahead of them. Use for community conditions like
    worker
    ,
    edge-light
    ,
    deno
    , or custom bundler conditions. Example:
    { "resolve": { "conditions": ["worker", "edge-light"] } }
Fallow从项目根目录读取配置,优先级为:
.fallowrc.json
>
fallow.toml
>
.fallow.toml
。借助90种自动检测的框架插件,大多数项目无需配置即可运行。
jsonc
{
  "$schema": "https://raw.githubusercontent.com/fallow-rs/fallow/main/schema.json",
  "entry": ["src/index.ts"],
  "ignorePatterns": ["**/*.generated.ts"],
  "ignoreDependencies": ["autoprefixer"],
  "publicPackages": ["@myorg/shared-lib"],
  "dynamicallyLoaded": ["plugins/**/*.ts"],
  "rules": {
    "unused-files": "error",
    "unused-exports": "warn",
    "unused-types": "off"
  }
}
规则取值:
"error"
(CI失败)、
"warn"
(仅报告)、
"off"
(跳过检测)。
配置字段说明:
  • publicPackages
    : 作为公共库的工作区包;这些包的导出项不会被标记为未使用
  • dynamicallyLoaded
    : 运行时加载的文件的通配符模式(插件目录、本地化文件);这些文件被视为始终在使用
  • usedClassMembers
    : 类方法/属性名称,用于扩展Angular/React内置生命周期允许列表,添加框架调用的名称。每个条目可以是普通字符串(全局抑制)或作用域对象
    { extends?, implements?, members }
    ,仅匹配具有指定继承关系的类。对于
    refresh
    execute
    等通用名称,使用作用域规则避免无关类的误报;对于
    agInit
    等唯一名称,使用全局字符串。示例:
    ["agInit", { "implements": "ICellRendererAngularComp", "members": ["refresh"] }, { "extends": "BaseCommand", "members": ["execute"] }]
    。未加约束的作用域规则(无
    extends
    implements
    )会在加载时被拒绝。对于库特定的允许列表,可在
    .fallow/plugins/*.jsonc
    文件中使用插件级的
    usedClassMembers
  • resolve.conditions
    : 模块解析时需要额外支持的package.json
    exports
    /
    imports
    条件名称。基线条件(
    development
    import
    require
    default
    types
    node
    ,以及RN/Expo环境下的
    react-native
    /
    browser
    )始终会被包含;用户添加的条件会前置到基线条件之前。用于支持社区条件如
    worker
    edge-light
    deno
    或自定义打包器条件。示例:
    { "resolve": { "conditions": ["worker", "edge-light"] } }

Inline suppression

内联抑制

typescript
// fallow-ignore-next-line
export const keepThis = 1;

// fallow-ignore-next-line unused-export
export const keepThisToo = 2;

// fallow-ignore-file
// fallow-ignore-file unused-export

// Mark as intentionally unused (tracked for staleness)
/** @expected-unused */
export const deprecatedHelper = () => {};
typescript
// fallow-ignore-next-line
export const keepThis = 1;

// fallow-ignore-next-line unused-export
export const keepThisToo = 2;

// fallow-ignore-file
// fallow-ignore-file unused-export

// 标记为有意未使用(会追踪是否过期)
/** @expected-unused */
export const deprecatedHelper = () => {};

Key Gotchas

关键陷阱

  • fix --yes
    is required
    in non-TTY (agent) environments. Without it,
    fix
    exits with code 2
  • Zero config by default. 90 framework plugins auto-detect. Don't create config unless customization is needed
  • Syntactic analysis only. No TypeScript compiler, so fully dynamic
    import(variable)
    is not resolved
  • Function overloads are deduplicated. TypeScript function overload signatures are merged into a single export (not reported as separate unused exports)
  • Re-export chains are resolved. Exports through barrel files are tracked, not falsely flagged
  • --changed-since
    is additive.
    Only new issues in changed files, not all issues in the project
For the full list with examples, see references/gotchas.md.
  • 非TTY(Agent)环境必须使用
    fix --yes
    。否则
    fix
    命令会以退出码2终止
  • 默认零配置。90种框架插件自动检测。除非需要自定义,否则无需创建配置文件
  • 仅语法分析。不使用TypeScript编译器,因此无法解析完全动态的
    import(variable)
  • 函数重载会被去重。TypeScript函数重载签名会合并为单个导出项(不会被报告为单独的未使用导出项)
  • 重导出链会被解析。桶文件的导出会被追踪,不会被误标记
  • --changed-since
    是增量式的
    。仅报告变更文件中的新问题,而非项目中的所有问题
完整示例请查看references/gotchas.md

Instructions

操作指南

  1. Identify the task from the user's request (audit, fix, find dupes, set up CI, migrate, debug)
  2. Run the appropriate command with
    --format json --quiet
  3. Use filter flags to limit output when the user asks about specific issue types
  4. Always dry-run before fix. Show the user what will change, then apply
  5. Report results clearly. Summarize issue counts, list specific findings, suggest next steps
  6. For false positives, suggest inline suppression comments or config rule adjustments
If
$ARGUMENTS
is provided, use it as the
--root
path or pass it as the target for the appropriate fallow command.
  1. 从用户请求中识别任务(审计、修复、查找重复代码、设置CI、迁移、调试)
  2. 运行相应的命令并添加
    --format json --quiet
    参数
  3. 使用过滤参数在用户询问特定问题类型时限制输出范围
  4. 执行修复前务必先干运行。向用户展示将变更的内容,然后再应用修复
  5. 清晰报告结果。总结问题数量,列出具体检测结果,建议下一步操作
  6. 对于误报,建议使用内联抑制注释或调整配置规则
如果提供了
$ARGUMENTS
,将其作为
--root
路径或传递给相应fallow命令的目标路径。",