depcheck、npm-check-updates、retire 和 snyk 都是用于提升 JavaScript/TypeScript 项目依赖健康度的命令行工具,但各自聚焦不同维度。depcheck 主要检测未使用的依赖项;npm-check-updates 聚焦于识别和升级过时的依赖版本;retire 专注于扫描已知漏洞的前端库(如 jQuery、Bootstrap);而 snyk 是一个综合性的安全平台,可检测并修复依赖中的安全漏洞,支持深度集成 CI/CD 流程。这些工具在现代前端工程化实践中常被组合使用,以构建更健壮、安全、轻量的依赖体系。
在现代前端工程中,依赖管理远不止 npm install —— 我们需要确保依赖被使用、保持更新、没有漏洞。depcheck、npm-check-updates、retire 和 snyk 正是从这四个角度切入的工具。它们不是互斥选项,而是互补组件。本文从真实开发场景出发,对比其核心能力、适用边界与技术细节。
depcheck:找出“僵尸依赖”depcheck 分析源码,识别 package.json 中声明但从未被 require/import 的依赖。这对清理历史包袱非常有用。
# 检查未使用依赖
npx depcheck
# 输出示例:
# Unused dependencies
# * lodash
# * moment
它会遍历所有 JS/TS/Vue/Svelte 等文件,解析 AST 判断是否真正引用了某个包。注意:它无法检测动态 require(如 require(someVar))或仅用于构建脚本的依赖。
npm-check-updates:一键升级过时依赖npm-check-updates(常缩写为 ncu)读取 package.json,对比 registry 中的最新版本,告诉你哪些包可以升级。
# 查看可升级的依赖
npx npm-check-updates
# 升级所有次要/补丁版本
npx npm-check-updates -u && npm install
它支持语义化版本策略(如只升 minor、或跳 major),还能交互式选择要升级的包。但它不修改 node_modules,只改 package.json,需手动 npm install。
retire:扫描前端库漏洞(尤其 CDN 场景)retire 专攻前端 JavaScript 库的安全漏洞,特别擅长检测 HTML 中直接引用的 CDN 脚本或本地 vendor 目录下的老版本库。
# 扫描 public/ 目录下的 JS/CSS
npx retire --path ./public
# 输出示例:
# jquery 1.6.2 has known vulnerabilities
它的漏洞数据库来自 retire.js 官方维护的 JSON 列表,覆盖 jQuery、Bootstrap、Angular 等经典库。但对于通过 npm 安装并由 bundler 处理的现代依赖(如 React 组件库),效果有限。
snyk:全链路依赖安全平台snyk 不仅扫描 package-lock.json 中的依赖树,还能检测间接依赖中的漏洞,并提供精确的修复建议(如“升级 [email protected] → [email protected] 可修复 CVE-XXXX”)。
# 扫描项目漏洞
npx snyk test
# 自动修复(生成补丁或升级)
npx snyk fix
它还支持监控仓库、PR 检查、Docker 镜像扫描等,是 DevSecOps 的标准组件。但需登录 Snyk 账户(免费 tier 有限额)。
| 能力 | depcheck | npm-check-updates | retire | snyk |
|---|---|---|---|---|
| 检测未使用依赖 | ✅ | ❌ | ❌ | ❌ |
| 检查依赖是否过时 | ❌ | ✅ | ❌ | ⚠️(仅关联漏洞时提示) |
| 扫描前端库漏洞(CDN/vendor) | ❌ | ❌ | ✅ | ⚠️(有限支持) |
| 扫描 npm 依赖树漏洞 | ❌ | ❌ | ❌ | ✅ |
| 提供自动修复方案 | ❌ | ✅(仅升级 package.json) | ❌ | ✅(含补丁) |
| 支持 CI/CD 集成 | ⚠️(需自定义) | ⚠️(需自定义) | ⚠️(基础) | ✅(原生支持) |
注意:截至 2024 年,
retire的 GitHub 仓库已归档(archived),官方标记为“不再积极维护”。虽然仍可使用,但不建议在新项目中采用,应优先考虑snyk或npm audit。
你接手一个三年前的老项目,package.json 有 80+ 个依赖,但很多可能没用。
# 1. 先用 depcheck 找出未使用依赖
npx depcheck
# 2. 手动移除无用项(谨慎!)
npm uninstall unused-pkg
# 3. 用 ncu 升级剩余依赖到最新兼容版
npx npm-check-updates -u
npm install
# 4. 用 snyk 扫描安全漏洞
npx snyk test
在 PR 合并前,自动检查漏洞和过时依赖。
# .github/workflows/ci.yml
steps:
- name: Check for vulnerabilities
run: npx snyk test --fail-on-issue
- name: Check outdated deps (non-blocking)
run: npx npm-check-updates || echo "Some deps are outdated"
这里不推荐在 CI 中自动运行 depcheck,因为误报可能导致误删关键依赖(如 Babel 插件仅在配置中引用)。
系统仍使用 jQuery 1.x 和 Bootstrap 3,通过 <script src="cdn/jquery.js"> 引入。
# retire 仍能发挥作用
npx retire --js --outputformat json > retire-report.json
但长远看,应迁移到 npm 管理依赖,并用 snyk 替代 retire。
depcheck 的盲区:无法识别通过 Webpack alias、动态 import 或仅在测试文件中使用的依赖。可通过 --ignores 排除已知误报。
npx depcheck --ignores "@types/*,eslint-*"
npm-check-updates 的风险:-u 参数会直接改写 package.json,若跳 major 版本可能导致破坏性变更。建议先用 ncu -i 交互式选择。
retire 的局限性:对 ES Module、Tree-shaking 后的代码无能为力。且漏洞库更新滞后,不如 Snyk/NVD 实时。
snyk 的权限要求:snyk fix 需要写入权限,且某些修复需付费 plan。开源项目可申请免费额度。
depchecknpm-check-updatesretire(仅限遗留系统),新项目跳过snyk在真实项目中,这四者往往协同工作:先用 depcheck 瘦身,再用 ncu 更新,最后用 snyk 把关安全。而 retire 作为历史工具,正逐步被更现代的方案取代。
最终建议:对于新项目,优先集成
snyk+npm-check-updates,辅以定期depcheck审计。避免在关键路径上依赖已归档的工具。
选择 depcheck 如果你需要清理项目中未实际引用的 npm 依赖(包括 devDependencies),从而减小 node_modules 体积、提升安装速度并降低潜在冲突风险。它特别适合在重构、迁移或长期维护的项目中做依赖瘦身,但不提供安全或版本更新建议。
选择 npm-check-updates 如果你的主要目标是将 package.json 中的依赖升级到最新兼容或最新主版本,尤其适用于定期维护项目依赖栈。它能清晰展示哪些包有新版本,并支持交互式升级,但不分析代码使用情况或安全问题。
选择 snyk 如果你需要企业级的依赖安全治理能力,包括自动检测漏洞、提供修复补丁(如通过 patch 或升级路径)、集成 CI/CD 和生成合规报告。它支持深度依赖树分析和运行时保护,但需注册账户,部分高级功能需付费,适合对安全性要求高的生产项目。
选择 retire 如果你维护的是传统前端项目(如使用 jQuery、AngularJS、Bootstrap 等),需要快速扫描静态资源中嵌入的已知漏洞库。它对 CDN 引用或本地 vendor 文件有效,但对现代模块化构建(如通过 webpack 打包的依赖)覆盖有限,且维护活跃度较低。
Depcheck is a tool for analyzing the dependencies in a project to see: how each dependency is used, which dependencies are useless, and which dependencies are missing from package.json.
npm install -g depcheck
Or simply using npx which is a package runner bundled in npm:
$ npx depcheck
Notice: depcheck needs node.js >= 10.
Depcheck not only recognizes the dependencies in JavaScript files, but also supports these syntaxes:
typescript dependency)@vue/compiler-sfc dependency)To get the syntax support by external dependency, please install the corresponding package explicitly. For example, for TypeScript user, install depcheck with typescript package:
npm install -g depcheck typescript
The special component is used to recognize the dependencies that are not generally used in the above syntax files. The following scenarios are supported by specials:
babel - Babel presets and pluginsbin - Dependencies used in npm commands, Travis scripts or other CI scriptscommitizen - Commitizen configuration adaptoreslint - ESLint configuration presets, parsers and pluginsfeross-standard - Feross standard format parsergatsby - Gatsby configuration parsergulp-load-plugins - Gulp-load-plugins lazy loaded pluginshusky - Husky configuration parseristanbul - Istanbul nyc configuration extensionsjest - Jest properties in Jest Configurationkarma - Karma configuration frameworks, browsers, preprocessors and reporterslint-staged - Lint-staged configuration parsermocha - Mocha explicit required dependenciesprettier - Prettier configuration moduletslint - TSLint configuration presets, parsers and pluginsttypescript - ttypescript transformerswebpack - Webpack loadersserverless- Serverless pluginsThe logic of a special is not perfect. There might be false alerts. If this happens, please open an issue for us.
depcheck [directory] [arguments]
The directory argument is the root directory of your project (where the package.json file is). If unspecified, defaults to current directory.
All of the arguments are optional:
--ignore-bin-package=[true|false]: A flag to indicate if depcheck ignores the packages containing bin entry. The default value is false.
--skip-missing=[true|false]: A flag to indicate if depcheck skips calculation of missing dependencies. The default value is false.
--json: Output results in JSON. When not specified, depcheck outputs in human friendly format.
--oneline: Output results as space separated string. Useful for copy/paste.
--ignores: A comma separated array containing package names to ignore. It can be glob expressions. Example, --ignores="eslint,babel-*".
--ignore-dirs: DEPRECATED, use ignore-patterns instead. A comma separated array containing directory names to ignore. Example, --ignore-dirs=dist,coverage.
--ignore-path: Path to a file with patterns describing files to ignore. Files must match the .gitignore spec. Example, --ignore-path=.eslintignore.
--ignore-patterns: Comma separated patterns describing files to ignore. Patterns must match the .gitignore spec. Example, --ignore-patterns=build/Release,dist,coverage,*.log.
--quiet: Suppress the "No depcheck issue" log. Useful in a monorepo with multiple packages to focus only on packages with issues.
--help: Show the help message.
--parsers, --detectors and --specials: These arguments are for advanced usage. They provide an easy way to customize the file parser and dependency detection. Check the pluggable design document for more information.
--config=[filename]: An external configuration file (see below).
Depcheck can be used with an rc configuration file. In order to do so, create a .depcheckrc file in your project's package.json folder, and set the CLI keys in YAML, JSON, and JavaScript formats.
For example, the CLI arguments --ignores="eslint,babel-*" --skip-missing=true would turn into:
.depcheckrc
ignores: ["eslint", "babel-*"]
skip-missing: true
Important: if provided CLI arguments conflict with configuration file ones, the CLI ones will take precedence over the rc file ones.
The rc configuration file can also contain the following extensions: .json, .yaml, .yml.
Similar options are provided to depcheck function for programming:
import depcheck from 'depcheck';
const options = {
ignoreBinPackage: false, // ignore the packages with bin entry
skipMissing: false, // skip calculation of missing dependencies
ignorePatterns: [
// files matching these patterns will be ignored
'sandbox',
'dist',
'bower_components',
],
ignoreMatches: [
// ignore dependencies that matches these globs
'grunt-*',
],
parsers: {
// the target parsers
'**/*.js': depcheck.parser.es6,
'**/*.jsx': depcheck.parser.jsx,
},
detectors: [
// the target detectors
depcheck.detector.requireCallExpression,
depcheck.detector.importDeclaration,
],
specials: [
// the target special parsers
depcheck.special.eslint,
depcheck.special.webpack,
],
package: {
// may specify dependencies instead of parsing package.json
dependencies: {
lodash: '^4.17.15',
},
devDependencies: {
eslint: '^6.6.0',
},
peerDependencies: {},
optionalDependencies: {},
},
};
depcheck('/path/to/your/project', options).then((unused) => {
console.log(unused.dependencies); // an array containing the unused dependencies
console.log(unused.devDependencies); // an array containing the unused devDependencies
console.log(unused.missing); // a lookup containing the dependencies missing in `package.json` and where they are used
console.log(unused.using); // a lookup indicating each dependency is used by which files
console.log(unused.invalidFiles); // files that cannot access or parse
console.log(unused.invalidDirs); // directories that cannot access
});
The following example checks the dependencies under /path/to/my/project folder:
$> depcheck /path/to/my/project
Unused dependencies
* underscore
Unused devDependencies
* jasmine
Missing dependencies
* lodash
It figures out:
underscore is declared in the package.json file, but not used by any code.jasmine is declared in the package.json file, but not used by any code.lodash is used somewhere in the code, but not declared in the package.json file.Please note that, if a subfolder has a package.json file, it is considered another project and should be checked with another depcheck command.
The following example checks the same project, however, outputs as a JSON blob. Depcheck's JSON output is in one single line for easy pipe and computation. The json command after the pipe is a node.js program to beautify the output.
$> depcheck /path/to/my/project --json | json
{
"dependencies": [
"underscore"
],
"devDependencies": [
"jasmine"
],
"missing": {
"lodash": [
"/path/to/my/project/file.using.lodash.js"
]
},
"using": {
"react": [
"/path/to/my/project/file.using.react.jsx",
"/path/to/my/project/another.file.using.react.jsx"
],
"lodash": [
"/path/to/my/project/file.using.lodash.js"
]
},
"invalidFiles": {
"/path/to/my/project/file.having.syntax.error.js": "SyntaxError: <call stack here>"
},
"invalidDirs": {
"/path/to/my/project/folder/without/permission": "Error: EACCES, <call stack here>"
}
}
dependencies, devDependencies and missing properties have the same meanings in the previous example.using property is a lookup indicating each dependency is used by which files.missing and using lookup is an array. It means the dependency may be used by many files.invalidFiles property contains the files having syntax error or permission error. The value is the error details. However, only one error is stored in the lookup.invalidDirs property contains the directories having permission error. The value is the error details.Depcheck just walks through all files and tries to find the dependencies according to some predefined rules. However, the predefined rules may not be enough or may even be wrong.
There may be some cases in which a dependency is being used but is reported as unused, or a dependency is not used but is reported as missing. These are false alert situations.
If you find that depcheck is reporting a false alert, please open an issue with the following information to let us know:
depcheck --json command. Beautified JSON is better.We use the GitHub release page to manage changelog.
This project exists thanks to all the people who contribute. [Contribute].
Become a financial contributor and help us sustain our community. [Contribute]
Support this project with your organization. Your logo will show up here with a link to your website. [Contribute]
MIT License.