You open node_modules, spot a package you never installed and wonder who brought it in. npm explain answers that, and it has the alias npm why. I’d run it before deleting anything from a dependency list.
Give it a package name and it prints the chain of dependencies that pulls it in:
npm explain glob
For every installed copy it shows the version, where it sits in node_modules, and the path back to your own package.json. The npm docs use glob in npm’s own source as the example: one copy is a dev dependency that arrives through rimraf, another through a different package.
That is useful in a few situations: a vulnerability report names a package you don’t recognize, a package appears twice in different versions, or you want to know whether removing a dependency would actually remove its sub-dependencies.
If the same package is installed more than once, you can explain one specific copy by passing its folder:
npm explain node_modules/some-package/node_modules/glob
Other options:
npm explain glob --json # machine-readable output
npm explain glob --workspace=app # limit to one workspace in a monorepo
Caveat: the command reads what is installed in node_modules, so run npm install first when you have just cloned a project. It explains why a package is there, not whether it is safe. For that, npm audit is the next step.
It is a good companion to npm ls --depth=0, which lists only the packages you asked for. Where ls shows what is installed, explain shows the reason.
Further reading: npm docs: npm explain