Table of Contents
Why we get “Error: Cannot find module”?
Working with Node can be a bit frustrating when dealing with error messages especially ones that have to deal with
Error: Cannot find module 'package-name' is a popular module error message that you might face when working with Node and its packages which comes most likely because of missing module which is required by the application.
In this article, we will discuss how to deal with handling this error message.
Solution: Install missing module using Node Package Manager
The Node Package Manager, popularly known as
npm is a command line tool that helps us to install, update or manage
Node.js packages. So, if you can’t find a module,
npm is our go-to guy to deal with this issue.
Method-1: npm install
The first approach is to check if we have the module or package at first or install the module directly. The command to perform this operation can be seen below.
npm install package-name
package-name is not installed, the output could look like this
7 packages are looking for funding run `npm fund` for details found 0 vulnerabilities
However, if you have it installed, it could look like this. Emphasis on the
up to date.
up to date, audited 58 packages in 1s 7 packages are looking for funding run `npm fund` for details
If you are trying to install a module that you created yourself or pulled from GitHub, you can go to root directory of the folder holding the
package.json file and execute the above command or the below
npm install ../package-name
or simply, the
npm install command, which accesses the
package.json file to see the modules needed.
Method-2: npm install -g
If the above section doesn’t work to solve the
Error: Cannot find module 'package-name' error message, you could try to install it globally. This allows us to use the module from any directory. To achieve this, we need to add the
-g flag to the
npm install -g express
There is a possibility that you are access the module from a directory that doesn’t have access to that module, and therefore, if you install globally, you can access the
Method-3: npm ci
Also, if the repository or project you are working with uses the
package-lock.json, you have to use another command other than
npm command appropriate for such scenarios can be seen below
Depending on the issue at hand, any of the above section could be useful to solve your
Error: Cannot find module 'package-name' error message. You can try out all of these approaches if you don’t know for sure what’s going on. However, it is important to know what each command does which has been explained.