Debugging npm - "Error: Cannot find module xxx"
11 January 2016
I recently had an issue where a CoffeeScript unit test I had written started throwing “Error: Cannot find module”. Here are the steps I used to resolve the issue.
TL;DR
Steps to try to resolve the issue:
- Ensure the module is installed.
- Clean the cache.
- Remove the
node_modulesdirectory and reinstall. - Check the package version number. Is it what you expected? Does a previous version of the package work?
Detailed steps
- Ensure the module is installed using the command:
npm list package_name. This will need to be run in the project’s directory, which should have anode_modulesdirectory andpackage.jsonfile in it. - Try cleaning the cache by using the command
npm cache clean. Aside: you can see where your cache is located with the commandnpm config get cache. - If that does not resolve the issue, npm may have gotten in a funk so try reinstalling the modules. In your project directory do the following:
rm -rf node_modules- this deletes thenode_modulesdirectory and all its content.npm cache clean- deletes the contents of the npm cache directory.npm install- reinstall all the packages for your project from it’spackage.jsonfile.
- If that does not resolve the issue, check if the package has recently been updated. If the versioning in the
package.jsonfile uses version ranges then a new version of the package may have been pulled recently. Check to see if that new version is actually valid. Does the process work if you use a previous version?
The final step is what resolved my issue for me. I was using version ranges in my package.json and had inadvertently obtained a new version of the package, which was broken.
