In the developer diary, we may face a common error: “Cannot find module.” This error occurs in all programs that we build, including me who has built about 10 to 20 projects. I have already cleared this error, but it still occurs.
As a developer, you know that when you deploy your code, you should run unit/integration tests to make sure everything is working as intended. But there is one type of error that eludes even the best of us: A missing module or dependency in our code.
Want to know the most common errors that occur when trying to install a module? How about how to fix them? In this guide, I’ll go over the 5 most common, and how to fix them.
1. Error Occurs When Failed Installing Dependency
When a first npm install fails, it’s best to remove the file and restart the process. This happens when a first npm install has crashed for some reason (SIGINT of npm), or that the delay was too long, or data is corrupted. Trying an npm install again won’t save the problem. Something got wrong on the npm first check, so the best choice is to remove the file and to restart npm install.
just in case you can run this code in 1 line command
npm uninstall PackageName && npm install PackageName --save
the code above can help you fix the problem when the installation is failed
2. The Package.json is has Error Unknown causes “cannot find module”
this problem is occurs when we start an npm to long and not restart it, by the way its look like we have no code error or all package is already placed in the right place. The problem is we had to reinstall our modules, this is easy but you need to check are the package you need is already in “dependency” bracket in package.json or not?, if its not there yet, insert the package you need then run this npm command in your command line.
rm -rf node_modules && rm -rf package-lock.json && npm install
and the problem that showing before will gone, and the program will clearly working
3. NodeJs Version is not supported in the Dependency
When you use nvm, make sure that the existing node_modules that are bindings to other libraries are compiled for the correct Node.js version.
I had the same issue. The reason was that we were running two applications on a server, one that required Node.js 5.6 because it used node-gd (which doesn’t run on Node.js 6 for now), and another that required Node.js 6. Node.js 6 is the default installation, but we installed it using apt-get .
4. Wrong Include Dependency Name File Or Function
Its already the most problem when a beginner calling some dependency but in the wrong way. If you are installing a module and it is missing or has an incorrect main field in its package.json, you will encounter this error. The module itself is installed, but npm/node must use a single .js file as an entrypoint to your module. If the main field is not there, it defaults to looking for index.js in your module’s folder. If your module’s main file is not called index.js, then you will encounter this error.