npm 中文文档 npm 中文文档
指南
npmjs.com (opens new window)
指南
npmjs.com (opens new window)
  • 快速入门

    • npm 是什么?
    • npm 安装和更新
    • npm 防止权限错误
    • npm package.json 文件
    • npm 安装包
    • npm 更新包
    • npm 卸载包
    • npm 创建 Node.js 模块
    • npm 发布和更新包
    • npm 使用语义化版本
    • npm 使用 Dist-tags 标记包
    • npm 包和模块的了解
  • 命令行
  • 配置 npm

depcheck


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.

Installation


  1. ``` sh
  2. npm install -g depcheck

  3. ```

Or simply using npx which is a package runner bundled in npm :

  1. ``` sh
  2. $ npx depcheck

  3. ```

Notice:depcheck needs node.js >= 10.

Syntax Support


Depcheck not only recognizes the dependencies in JavaScript files, but also supports these syntaxes:

JavaScript (ES5, ES6 and ES7)
React JSX
CoffeeScript
TypeScript (with typescript dependency)
SASS and SCSS (with node-sass dependency)
Vue.js (with @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:

  1. ``` sh
  2. npm install -g depcheck typescript

  3. ```

Special


The specialcomponent 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 plugins
bin - Dependencies used in npm commands, Travis scripts or other CI scripts
commitizen - Commitizen configuration adaptor
eslint - ESLint configuration presets, parsers and plugins
feross-standard - Feross standard format parser
gatsby - Gatsby configuration parser
gulp-load-plugins - Gulp-load-plugins lazy loaded plugins
husky - Husky configuration parser
istanbul - Istanbul nyc configuration extensions
jest - Jest properties in Jest Configuration
karma - Karma configuration frameworks, browsers, preprocessors and reporters
lint-staged - Lint-staged configuration parser
mocha - Mocha explicit required dependencies
prettier - Prettier configuration module
tslint - TSLint configuration presets, parsers and plugins
ttypescript - ttypescript transformers
webpack - Webpack loaders
serverless - Serverless plugins

The logic of a special is not perfect. There might be false alerts. If this happens, please open an issue for us.

Usage


  1. ``` sh
  2. depcheck [directory] [arguments]

  3. ```

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.

--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).

Usage with a configuration file


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

  1. ``` sh
  2. ignores: ["eslint", "babel-*"]
  3. skip-missing: true

  4. ```

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.

API


Similar options are provided to depcheck function for programming:

  1. ``` js
  2. import depcheck from 'depcheck';

  3. const options = {
  4.   ignoreBinPackage: false, // ignore the packages with bin entry
  5.   skipMissing: false, // skip calculation of missing dependencies
  6.   ignorePatterns: [
  7.     // files matching these patterns will be ignored
  8.     'sandbox',
  9.     'dist',
  10.     'bower_components',
  11.   ],
  12.   ignoreMatches: [
  13.     // ignore dependencies that matches these globs
  14.     'grunt-*',
  15.   ],
  16.   parsers: {
  17.     // the target parsers
  18.     '**/*.js': depcheck.parser.es6,
  19.     '**/*.jsx': depcheck.parser.jsx,
  20.   },
  21.   detectors: [
  22.     // the target detectors
  23.     depcheck.detector.requireCallExpression,
  24.     depcheck.detector.importDeclaration,
  25.   ],
  26.   specials: [
  27.     // the target special parsers
  28.     depcheck.special.eslint,
  29.     depcheck.special.webpack,
  30.   ],
  31.   package: {
  32.     // may specify dependencies instead of parsing package.json
  33.     dependencies: {
  34.       lodash: '^4.17.15',
  35.     },
  36.     devDependencies: {
  37.       eslint: '^6.6.0',
  38.     },
  39.     peerDependencies: {},
  40.     optionalDependencies: {},
  41.   },
  42. };

  43. depcheck('/path/to/your/project', options).then((unused) => {
  44.   console.log(unused.dependencies); // an array containing the unused dependencies
  45.   console.log(unused.devDependencies); // an array containing the unused devDependencies
  46.   console.log(unused.missing); // a lookup containing the dependencies missing in `package.json` and where they are used
  47.   console.log(unused.using); // a lookup indicating each dependency is used by which files
  48.   console.log(unused.invalidFiles); // files that cannot access or parse
  49.   console.log(unused.invalidDirs); // directories that cannot access
  50. });
  51. ```

Example


The following example checks the dependencies under /path/to/my/project folder:

  1. ``` shell
  2. $> depcheck /path/to/my/project
  3. Unused dependencies
  4. * underscore
  5. Unused devDependencies
  6. * jasmine
  7. Missing dependencies
  8. * lodash
  9. ```

It figures out:

The dependency underscore is declared in the package.json file, but not used by any code.
The devDependency jasmine is declared in the package.json file, but not used by any code.
The dependency 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.

  1. ``` js
  2. $> depcheck /path/to/my/project --json | json
  3. {
  4.   "dependencies": [
  5.     "underscore"
  6.   ],
  7.   "devDependencies": [
  8.     "jasmine"
  9.   ],
  10.   "missing": {
  11.     "lodash": [
  12.       "/path/to/my/project/file.using.lodash.js"
  13.     ]
  14.   },
  15.   "using": {
  16.     "react": [
  17.       "/path/to/my/project/file.using.react.jsx",
  18.       "/path/to/my/project/another.file.using.react.jsx"
  19.     ],
  20.     "lodash": [
  21.       "/path/to/my/project/file.using.lodash.js"
  22.     ]
  23.   },
  24.   "invalidFiles": {
  25.     "/path/to/my/project/file.having.syntax.error.js": "SyntaxError: <call stack here>"
  26.   },
  27.   "invalidDirs": {
  28.     "/path/to/my/project/folder/without/permission": "Error: EACCES, <call stack here>"
  29.   }
  30. }
  31. ```

The dependencies, devDependencies and missing properties have the same meanings in the previous example.
The using property is a lookup indicating each dependency is used by which files.
The value of missing and using lookup is an array. It means the dependency may be used by many files.
The 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.
The invalidDirs property contains the directories having permission error. The value is the error details.

False Alert


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 alertsituations.

If you find that depcheck is reporting a false alert, please open an issue with the following information to let us know:

The output from depcheck --json command. Beautified JSON is better.
Which dependencies are considered as false alert?
How are you using those dependencies, what do the files look like?

Changelog


We use the GitHub release page to manage changelog.
Last Updated: 2023-05-15 10:22:02