Table of Contents
When you are working in Node, you will sometimes encounter the error Cannot find module 'module-name'
with the error code MODULE_NOT_FOUND
.
The error looks like this:
BASHinternal/modules/cjs/loader.js:796
throw err;
^
Error: Cannot find module 'module'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:793:17)
at Function.Module._load (internal/modules/cjs/loader.js:686:27)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
In this post, we'll learn how to resolve this error.
What is the problem?
The issue is that Node is unable to find the module that you are trying to import into your Node application.
The most common reason for this is that you simply haven't installed the project's dependencies yet.
The project's dependencies are listed in the package.json
file at the root of the project.
The Solution
To fix the Cannot find module
error, simply install the missing modules using npm
.
To so, you can use the following command:
BASHnpm install
If you are using the yarn
package manager, you can use the following command:
BASHyarn install
This will install the project's dependencies into your project so that you can use them.
Sometimes, this might still not resolve it for you. In this case, you'll want to just delete your node_modules
folder and lock file (package-lock.json
or yarn.lock
) and try again.
This is how you can delete the node_modules
folder and lock files:
BASHrm -rf node_modules
rm package-lock.json
rm yarn.lock
Local files
If your module is not coming from a remote source, you are seeing the error because the path to the local file is not correct.
Try to confirm that the path pointing to the local module is correct and your error should be resolved.
Conclusion
The Cannot find module
error is a common error that usually happens when dependencies are not installed. Once you install your dependencies and ensure that the paths are correct, you can resolve the error and run your application successfully.
Hopefully, this resolved the issue for you.
Thanks for reading!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- How to Set Up Cron Jobs in Linux
- How to deploy a PHP app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Building a Real-Time Note-Taking App with Vue and Firebase
- How To Create a Modal Popup Box with CSS and JavaScript
- Getting Started with Moon.js