Find unused npm packages in package.json

Is there a way to determine if you have package in package.json that are not longer needed?

For instance when trying out a package and later commenting or deleting code, but forgetting to uninstall it I end up with a couple packages that could be deleted. What would be an efficient way to determine if a package could safely be deleted?

You can use an npm module called depcheck.

  1. Install the module:

    npm install depcheck -g
    
  2. Run it and find the unused dependencies:

    depcheck
    

The good thing about this approach is that you don't have to remember the find or grep command.

There is also a package called npm-check:

npm-check

Check for outdated, incorrect, and unused dependencies.

enter image description here

It is quite powerful and actively developed. One of it's features it checking for unused dependencies - for this part it uses the depcheck module mentioned in the other answer.

If you're using a Unix like OS (Linux, OSX, etc) then you can use a combination of find and egrep to search for require statements containing your package name:

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'name-of-package' {} \;

If you search for the entire require('name-of-package') statement, remember to use the correct type of quotation marks:

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni 'require("name-of-package")' {} \;

or

find . -path ./node_modules -prune -o -name "*.js" -exec egrep -ni "require('name-of-package')" {} \;

The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json and check them. You need to do this for each package yourself. Since package.json is just JSON this could be remedied by writing a small script that uses child_process.exec to run this command for each dependency. And make it a module. And add it to the NPM repo...