Registry / devops / depcheck

depcheck

JSON →
library0.3.2jsnpmunverified

Depcheck is a widely used command-line interface (CLI) tool and programmatic library for analyzing Node.js project dependencies. Its primary function is to identify unused dependencies, detect missing dependencies required by the codebase, and provide insights into how declared dependencies are actually utilized. The current stable version is 1.4.7. While not adhering to a strict release schedule, the project is actively maintained, with multiple patch releases in 2023 and 2021, and significant updates including a breaking change in 2020 (v1.3.x). A key differentiator for Depcheck is its extensive syntax support, covering not only standard JavaScript (ES5-ES7) and React JSX but also CoffeeScript, TypeScript, SASS/SCSS, and Vue.js. Furthermore, it includes 'special' components designed to recognize dependencies used within various configuration files for tools like Babel, ESLint, Webpack, Jest, and Serverless, moving beyond basic `import` or `require` statements. This comprehensive analysis helps developers maintain leaner, more efficient codebases by facilitating the removal of unnecessary packages, which can improve performance and reduce bundle sizes.

npm install depcheck
INSTALL
IMPORT
SIG · DEPCHECK
D
depcheck
devopsjavascriptv0.3.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

depcheck
import depcheck from 'depcheck'; // Or for CommonJS: // const depcheck = require('depcheck');
import { depcheck } from 'depcheck';
The primary export is a default function (or CommonJS module.exports), which is typically imported directly or via `require`. Named imports are incorrect for the main function.
DepcheckOptions
import type { Options as DepcheckOptions, Results as DepcheckResults } from 'depcheck';
import { DepcheckOptions } from 'depcheck';
TypeScript types for options and results are available as named exports prefixed with 'Options' and 'Results' respectively, but should be imported as types to avoid runtime issues if not tree-shaken.
depcheck.parser
import depcheck from 'depcheck'; // ... then access parsers via depcheck.parser.jsx or similar
When imported programmatically, advanced configurations like custom parsers are accessed as properties on the main 'depcheck' function, e.g., `depcheck.parser.jsx`.

This quickstart demonstrates how to programmatically execute `depcheck` on a project directory, capturing and logging its findings regarding unused, missing, and used dependencies in JSON format. It highlights common configuration options for ignoring specific files or directories and provides a basic structure for handling results.

import depcheck from 'depcheck'; import path from 'path'; interface DepcheckResults { dependencies: string[]; devDependencies: string[]; missing: { [key: string]: string[] }; using: { [key: string]: string[] }; invalidDirs: { [key: string]: string }; invalidFiles: { [key: string]: string }; } async function runDepcheck(projectRoot: string): Promise<void> { const options = { ignoreBinPackage: false, // ignore the packages with bin entry skipMissing: false, // skip calculation of missing dependencies json: true, // output results in JSON format ignorePatterns: [ 'dist', // ignore build output directory 'coverage', // ignore coverage directory '*.log' // ignore log files ], // Add 'typescript' if you have TypeScript files and it's not a direct dependency // 'parsers': { '*.ts': depcheck.parser.typescript }, // 'specials': [depcheck.special.eslint, depcheck.special.webpack] // example specials }; try { const results: DepcheckResults = await depcheck(projectRoot, options) as any; // Cast to any due to programmatic type nuances if (results.dependencies.length > 0) { console.log('Unused dependencies:', results.dependencies); } if (results.devDependencies.length > 0) { console.log('Unused devDependencies:', results.devDependencies); } if (Object.keys(results.missing).length > 0) { console.log('Missing dependencies:', results.missing); } if (Object.keys(results.using).length > 0) { console.log('Dependencies in use (example):', Object.keys(results.using).slice(0, 2)); } if (results.dependencies.length === 0 && results.devDependencies.length === 0 && Object.keys(results.missing).length === 0) { console.log('No depcheck issues found for this project.'); } } catch (error) { console.error('Depcheck encountered an error:', error); } } // Example usage: Point to a dummy project root (create a package.json and some files) // In a real scenario, this would be your actual project directory. const dummyProjectRoot = path.resolve(process.cwd(), 'temp-depcheck-project'); console.log(`Running depcheck in: ${dummyProjectRoot}`); // Create a dummy package.json and an index.ts/js to simulate a project // This part would typically be part of your project setup, not quickstart code. // For demonstration, assume a basic project structure already exists. // To make this runnable, ensure a 'temp-depcheck-project' exists with a package.json // Example setup: // mkdir temp-depcheck-project // cd temp-depcheck-project // echo '{ "name": "test-project", "version": "1.0.0", "dependencies": { "lodash": "^4.17.21" }, "devDependencies": { "jest": "^29.0.0" } }' > package.json // echo 'import { get } from "lodash"; console.log(get({}, "a"));' > index.js // echo 'const sum = require("non-existent-pkg");' > another.js // npm install runDepcheck(process.cwd()); // Or specify a relative path to your project
depcheck --version
Debug
Known issues
breakingThe configuration for custom parsers changed significantly in versions 1.3.0 and 1.3.1. If you use `depcheck` programmatically or via a configuration file, the `parsers` key syntax shifted from using single asterisk `*.js` to double asterisk `**/*.js` glob patterns.
fix
Update your `.depcheckrc` or programmatic `options.parsers` configuration to use `**/*.js` (or similar) instead of `*.js` for glob patterns.
affects: >=1.3.0 <1.4.0
gotchaFor `depcheck` to properly analyze TypeScript or Vue.js files, you must explicitly install the `typescript` and/or `@vue/compiler-sfc` packages as dependencies in your project, even if they are already present as devDependencies. `depcheck` relies on these external packages for syntax support.
fix
Run `npm install --save-dev typescript @vue/compiler-sfc` (or `yarn add -D typescript @vue/compiler-sfc`) in your project root to ensure these peer dependencies are available to `depcheck`.
affects: >=1.0.0
gotchaDepcheck can produce 'false positives' for dependencies that are used indirectly, dynamically, or within specific configuration files (e.g., Jest typings, ESLint plugins, Webpack loaders) not fully covered by its 'special' component logic. While many common cases are handled, complex setups may require manual intervention.
fix
Utilize the `--ignores` CLI option or the `ignore` property in a `.depcheckrc` configuration file to explicitly tell `depcheck` to disregard specific packages that are validly used but misidentified as unused. For directories, use `--ignore-patterns`.
affects: >=1.0.0
gotchaDepcheck requires Node.js version 10 or higher. Running it with older Node.js versions will result in execution errors or unexpected behavior.
fix
Ensure your project's Node.js environment is version 10 or newer. Use a Node.js version manager like `nvm` to switch to a compatible version.
affects: <1.0.0
gotchaWhen working in monorepos or projects with multiple `package.json` files, `depcheck` might incorrectly report dependencies as unused if it doesn't correctly resolve imports across sub-projects or local packages. Running `depcheck` from the root may not capture all nuances of nested `package.json` files.
fix
Consider running `depcheck` within each sub-project directory or configure it to `--ignore-patterns` that contain other `package.json` files. Tools like `lerna` or `nx` often provide mechanisms to run scripts like `depcheck` across individual packages.
affects: >=1.0.0
gotchaWhile versions 1.4.7 and later support `package.json` subpath imports, complex aliasing, or TypeScript `paths` configurations can still lead to misidentification of dependencies or parsing failures if not correctly resolved by `depcheck`'s internal mechanisms.
fix
Verify that your `tsconfig.json` `paths` and `package.json` `imports` configurations are standard and well-formed. If issues persist, consider adding problematic paths or modules to the `--ignores` or `ignorePatterns` configuration.
affects: >=1.4.7
Errors
Common errors & fixes
TypeError: depcheck is not a function
Attempting to use `depcheck` programmatically with incorrect import syntax, such as a named import `import { depcheck }` when it is a default export, or using `require()` incorrectly in an ESM context.
fix
For ESM, use `import depcheck from 'depcheck';`. For CommonJS, use `const depcheck = require('depcheck');`. Ensure your `tsconfig.json` `esModuleInterop` is enabled for TypeScript.
Cannot find module 'typescript' or Cannot find module '@vue/compiler-sfc'
Depcheck encounters TypeScript or Vue.js files but the necessary compiler/parser packages (e.g., `typescript`, `@vue/compiler-sfc`) are not installed as direct dependencies in the project.
fix
Install the missing package(s) using `npm install --save-dev typescript @vue/compiler-sfc` (or `yarn add -D typescript @vue/compiler-sfc`).
Depcheck reports 'lodash' as unused, but it's used in my `.eslintrc.js`.
A dependency is used within a configuration file (like ESLint, Webpack, Jest, Babel) that `depcheck`'s default 'special' component logic doesn't fully cover or is misconfigured.
fix
Add the reported package to the `--ignores` CLI option or the `ignore` array in a `.depcheckrc` configuration file. You can also explicitly enable or configure `specials` via `options.specials` in programmatic use or `parsers` option.
Depcheck fails with 'Unexpected token '.' ' or 'SyntaxError: Cannot use import statement outside a module'
The project uses modern JavaScript/TypeScript syntax (e.g., top-level `await`, `satisfies` operator) or ESM-only `next.config.js` files that older versions of `depcheck` or its underlying parsers could not handle.
fix
Upgrade `depcheck` to the latest version (`npm install depcheck@latest`) as many parsing issues, including those related to ESM config files and newer TypeScript syntax, have been resolved in recent releases (e.g., `v1.4.3`, `v1.4.4`).
Depcheck takes a very long time to run or runs out of memory.
The project contains very large directories (e.g., build outputs, extensive temporary files, large `node_modules` not properly ignored) or has a complex dependency graph that `depcheck` attempts to process unnecessarily.
fix
Use the `--ignore-patterns` CLI option or `ignorePatterns` in a `.depcheckrc` file to exclude large directories (e.g., `dist`, `build`, `generated`) and file types (e.g., `*.log`, `*.tmp`) from the analysis. Ensure `node_modules` is implicitly ignored (which it usually is by default).
Upgrade
Version history
0.3.2latest on npm
Audit
Dependencies
typescriptrequiredRequired for parsing TypeScript files.
@vue/compiler-sfcrequiredRequired for parsing Vue.js Single File Components.
Agent activity
23 hits · last 30 days
node
22
Resources