when I run this command in my project:
yarn eject
shows this eror:
[root@VM-0-16-centos cruise-web]# yarn eject
yarn run v1.22.10
$ react-scripts eject
internal/modules/cjs/loader.js:834
throw err;
^
Error: Cannot find module 'react-dev-utils/inquirer'
Require stack:
- /home/dolphin/sync/source/cruise-web/node_modules/react-scripts/scripts/eject.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:831:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Module.require (internal/modules/cjs/loader.js:903:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/dolphin/sync/source/cruise-web/node_modules/react-scripts/scripts/eject.js:23:18)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/home/dolphin/sync/source/cruise-web/node_modules/react-scripts/scripts/eject.js'
]
}
then I add a dependency in my package.json
:
"react-dev-utils":"11.0.1"
then run the command to install and rerun eject:
yarn
yarn eject
but the problem still not fixed, what should I do to make it work?
Содержание
- 初始化项目异常:Error: Cannot find module ‘inquirer’ #363
- Comments
- Cannot find module ‘inquirer’ #55
- Comments
- Create cordova project
- Beware of hidden file
- Grunt task for build and package
- Install dependency modules
- For toast browser simulator
- Mandatory plugins for using browser simulator (not for other platforms)
- Add toast plugin
- yarn update fails with «cannot find module ‘inquirer’» #1420
- Comments
- Expected Behavior
- Current Behavior
- Failure Information (for bugs)
- Steps to Reproduce
- Context
- Failure Logs
- Other
- How to resolve «Cannot find module» error in Node
- What is the problem?
- The Solution
- Local files
- Conclusion
初始化项目异常:Error: Cannot find module ‘inquirer’ #363
`➜ github node -v
v9.11.1
➜ github npm -v
5.6.0
➜ github weex create awesome-project
internal/modules/cjs/loader.js:550
throw err;
^
Error: Cannot find module ‘inquirer’
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
at Function.Module._load (internal/modules/cjs/loader.js:475:25)
at Module.require (internal/modules/cjs/loader.js:598:17)
at require (internal/modules/cjs/helpers.js:11:18)
at Object. (/usr/local/lib/node_modules/weex-toolkit/node_modules/_xtoolkit@1.0.3@xtoolkit/lib/installer/index.js:1:80)
at Module._compile (internal/modules/cjs/loader.js:654:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
at Module.load (internal/modules/cjs/loader.js:566:32)
at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
at Function.Module._load (internal/modules/cjs/loader.js:498:3)`
The text was updated successfully, but these errors were encountered:
@wzlee Please provide your weex version, run weex -v and show me the log.
+1 weex -v 也是上面的错,新装
Error: Cannot find module ‘inquirer’
+1 npm install -g weex-toolkit
module.js:545
throw err;
^
Error: Cannot find module ‘inquirer’
at Function.Module._resolveFilename (module.js:543:15)
at Function.Module._load (module.js:470:25)
at Module.require (module.js:593:17)
at require (internal/module.js:11:18)
at Object. (/usr/local/lib/node_modules/weex-toolkit/node_modules/_xtoolkit@1.0.3@xtoolkit/lib/installer/index.js:1:80)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
works at node 7.9.0
@zhaiduo @wzlee @zhoufengjob @k06a
I found this to be related to the strange dependency installation of the npm5+ version, there are many Cannot find module issues here npm/issues/16991.
You can downgrade to use npm4 to fix this problem, and I’ve also provided tips on the latest tool versions.
Источник
Cannot find module ‘inquirer’ #55
I’m getting Cannot find module ‘inquirer’ with grunt commands when trying to prepare or build.
What am I missing ?
The text was updated successfully, but these errors were encountered:
Hi 😀
In this case if inquirer module is not installed, It might be shown error such as «Cannot find module ‘inquirer’».
Can you check again whether you installed all dependent modules with ‘npm install’ command.
Can you check whether «inquire» directory is exist on your [project root]/node_modules.
If all above things are good, please upload your application as zip file.
Did you get this figured out? I’m having the same issue. «inquirer» is in my node_modules folder. I’ve deleted and reinstalled the node_modules folder to no avail. What should I do?
Hi
Please check «create empty project» in Wiki
url : https://github.com/Samsung/cordova-plugin-toast/wiki/Create-Project
If you did it, you can find «inquirer» in node_modules folder.
Create cordova project
$ cordova create TestApp
$ cd TestApp
$ cp -rf ../grunt-cordova-sectv/sample/. ./
$ npm install ../grunt-cordova-sectv
Grunt task for build and package
Install dependency modules
For toast browser simulator
$ cordova platform add browser
Mandatory plugins for using browser simulator (not for other platforms)
$ cordova plugin add cordova-plugin-device
$ cordova plugin add cordova-plugin-network-information
$ cordova plugin add cordova-plugin-globalization
Add toast plugin
$ cordova plugin add ../cordova-plugin-toast
@dholbrook86 I had to execute npm install inquirer in all the repos in toast folder and it worked
@AhmedGamal-Inmobly I did that. So I thought. I really thought I tried everything. Ended up moving on to something else. I was just experimenting anyway. I will have to come back to it later. Thanks for responding though! I appreciate it.
@pwsses Following those guidelines; I still end up with Warning: Cannot find module ‘inquirer’ Use —force to continue. when running grunt sectv-prepare:tv-webos and related commands. The module is in node_modules directory.
i have the same issue
i installed in all repos the following
- inquirer
- zip-dir
- xml2js
- js2xmlparser
- mustache
@rikoopa Thanks for this. Actually, I just needed to do this in toast/grunt-cordova-sectv , so, for anyone coming later:
This seems to get rid of the issue.
After solving «inquirer», now I get an error Unexpected token <.
Does the same thing happen to you?
Any ideas ?
I think it has to do with the grunt-cordova-sectv that does not work
grunt sectv-build —verbose —force
Initializing
Command-line options: —verbose, —force
Reading «Gruntfile.js» Gruntfile. OK
Registering Gruntfile tasks.
Initializing config. OK
Источник
yarn update fails with «cannot find module ‘inquirer’» #1420
Expected Behavior
To update to latest
Current Behavior
Failure Information (for bugs)
Steps to Reproduce
Please provide detailed steps for reproducing the issue.
Context
Please provide any relevant information about your setup:
- version of Nx used see package.json
- version of Angular CLI used 8.0.0
- angular.json configuration see above
- version of Angular DevKit used see above
- 3rd-party libraries and their versions see above
- and most importantly — a use-case that fails yarn update
A minimal reproduce scenario using allows us to quickly confirm a bug (or point out coding problem) as well as confirm that we are fixing the right problem.
Failure Logs
Please include any relevant log snippets or files here.
Other
Any other relevant information that will help us help you.
The text was updated successfully, but these errors were encountered:
Thank you for reporting this issue!
Please provide a repro so I can take a look.
I see you are on version 6 🙂 ideally this would work but there might be issues. It may be easier for you to go to 7.8.6 first via:
@FrozenPandaz thank you for your reply.
I’ve tried what you suggested but I get a new error
Invalid migration version: «8-beta»
Here’s the full log for the commands you suggest
I was able to go from 6.2.0 to 6.4.0 using altered versions of your commands.
Then was able to go from 6.4.0 to 6.4.1 using altered versions of your commands.
Then going from 6.4.0 to 7.8.6 I get different errors again, I’ll look at trying to correct them
We have another nrwl nx project that is newer, 7.7.0. doing yarn update also failed with:
I fixed the way the migrations work so now you should be able to do ng update @nrwl/schematics —force from a Nx 6.x workspace.
This will update you all the way up to the latest version! 🎉
Also, I recognize that some people might prefer to move from 6 to 7. This process is more complicated at the moment. I will work on porting the fix to a 7.8.7 version. I hope to finish this week or next week 😅 . In theory (I haven’t tested it yet), you should be able to do something like ng update @nrwl/workspace@7.8.7
In the meantime, for the daring, here is a process that might work. I know the following process is way too complicated so I would recommend waiting for the nicer solution.
Still hitting the same issue?
Hey, I’m a co-worker of @philjones88 , I hit this too but also had a require stack printed out incase that helps
Sorry, I forgot to mention you still need a compatible version of @angular/cli .
Please let me know if this works.
@FrozenPandaz we managed to muddle through an nrwl 6 to 8 update but it errors on our other project going from 7.7.0 to latest
log after trying again with the latest 7.8.7 and 8.1.2 releases
Same problem here but with npm and update from 7.8.5 to 8.1.2:
Cannot find module ‘inquirer’
Why does it say: Updating @angular/core to 8.0.0 when @angular/core was already at version 8.0.1 ?
Why does running ng update after ng update @nrwl/schematics still report @nrwl/angular 8.0.0 -> 8.1.2 when it actually had been updated already to 8.1.2?
4 but none is installed. You must install peer dependencies yourself. npm WARN worker-plugin@3.1.0 requires a peer of webpack@>= 4 but none is installed. You must install peer dependencies yourself. npm WARN @nrwl/angular@8.0.0 requires a peer of jasmine-marbles@
0.4.0 but none is installed. You must install peer dependencies yourself. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.7 (node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.7: wanted <«os»:»darwin»,»arch»:»any»>(current: <«os»:»linux»,»arch»:»x64″>) removed 195 packages, updated 14 packages and audited 870366 packages in 15.597s found 3 vulnerabilities (1 low, 1 moderate, 1 high) run `npm audit fix` to fix them, or `npm audit` for details Updating @angular/core to 8.0.0 Repository is not clean. Update changes will be mixed with pre-existing changes. Using package manager: ‘npm’ Collecting installed dependencies. Found 41 dependencies. Fetching dependency metadata from registry. UPDATE package.json (2637 bytes) npm WARN @ngtools/webpack@8.0.3 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN @nrwl/angular@8.0.0 requires a peer of jasmine-marbles@
0.4.0 but none is installed. You must install peer dependencies yourself. npm WARN ajv-keywords@3.4.0 requires a peer of ajv@^6.9.1 but none is installed. You must install peer dependencies yourself. npm WARN circular-dependency-plugin@5.0.2 requires a peer of webpack@>=4.0.1 but none is installed. You must install peer dependencies yourself. npm WARN codelyzer@4.5.0 requires a peer of @angular/compiler@>=2.3.1 7.0.0-beta =2.3.1 7.0.0-beta =1.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-dev-middleware@3.6.2 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-dev-server@3.1.14 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-dev-middleware@3.4.0 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-subresource-integrity@1.1.0-rc.6 requires a peer of webpack@^1.12.11 ||
4 but none is installed. You must install peer dependencies yourself. npm WARN worker-plugin@3.1.0 requires a peer of webpack@>= 4 but none is installed. You must install peer dependencies yourself. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.7 (node_modules/fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.7: wanted <«os»:»darwin»,»arch»:»any»>(current: <«os»:»linux»,»arch»:»x64″>) audited 870366 packages in 9.7s found 3 vulnerabilities (1 low, 1 moderate, 1 high) run `npm audit fix` to fix them, or `npm audit` for details Updating @angular/cli to 8.0.1 Repository is not clean. Update changes will be mixed with pre-existing changes. Using package manager: ‘npm’ Collecting installed dependencies. Found 41 dependencies. Fetching dependency metadata from registry. UPDATE package.json (2637 bytes) npm WARN @ngtools/webpack@8.0.3 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN @nrwl/angular@8.0.0 requires a peer of jasmine-marbles@
0.4.0 but none is installed. You must install peer dependencies yourself. npm WARN ajv-keywords@3.4.0 requires a peer of ajv@^6.9.1 but none is installed. You must install peer dependencies yourself. npm WARN circular-dependency-plugin@5.0.2 requires a peer of webpack@>=4.0.1 but none is installed. You must install peer dependencies yourself. npm WARN codelyzer@4.5.0 requires a peer of @angular/compiler@>=2.3.1 7.0.0-beta =2.3.1 7.0.0-beta =1.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-dev-middleware@3.6.2 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-dev-server@3.1.14 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-dev-middleware@3.4.0 requires a peer of webpack@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-subresource-integrity@1.1.0-rc.6 requires a peer of webpack@^1.12.11 ||
Источник
How to resolve «Cannot find module» error in Node
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:
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:
If you are using the yarn package manager, you can use the following command:
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:
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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Give feedback on this page , tweet at us, or join our Discord !
Источник
If you’re a developer that works with Node JS and JavaScript libraries and frameworks like React, Vue, and Angular, then you might have encountered the «Error: cannot find module» error.
In this article, I’m going to show you how to fix the error.
Why the «Error: cannot find module» Occurs
This error occurs because of the following reasons:
- you’re trying to import an item from a module you don’t have installed in your project directory
- you’re importing some things from an outdated package
- you’re pointing to a file that does not exist
In the screenshot below, you can see that I’m getting the error:
I’m getting the error because I’m trying to import the freeCodeCamp icon from the react-icons package, which I don’t have installed.
import { FaFreeCodeCamp } from "react-icons/fa";
How to Fix the «cannot find module» Error
If you get this error, the solution is always in the error. The module (package) not found is always specified in the format «Module not found: Error: Can’t resolve ‘package name’ in ‘project directory».
In my case, I got it like this «Module not found: Error: Can’t resolve ‘react-icons/fa’ in ‘C:UsersuserDesktopProjectsAddress Locatoraddress-locatorsrc'».
To fix the error, you need to install the package that is absent in your project directory – npm install package-name
or yarn add package-name
.
In my case, I need to install the react-icons
package so the freeCodeCamp icon can be resolved. I’ll do that by running yarn add react-icons
.
Once I install the package and run the app, everything should successfully compile:
If you install the package but you still get the error, then follow the steps below:
- delete the node modules folder by running
rm -rf node_modules
- delete package.lock.json file by running
rm -f package-lock.json
- clean up the NPM cache by running
npm cache clean --force
- install all packages again by running
npm install
That should fix the error for you.
Conclusion
When you get the “cannot find module” error, or “module not found”, it means you’ve not installed the package you’re trying to use.
If the error occurs even if you have the package installed, then the fixes suggested in this article can help you out.
Thank you for reading.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
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:
internal/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:
npm install
If you are using the yarn
package manager, you can use the following command:
yarn 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:
rm -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!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
-
Support Us
-
Join
-
Share
-
Tweet
-
Share
Give feedback on this page!
✋ Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza
“Error: cannot find module” occurs when you try to load a non-existant module in Node – Either via ESM (ECMAScript Modules) or CommonJS module systems.
The error usually looks like this in the console:
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module '/var/www/scripts/app.js'
Enter fullscreen mode
Exit fullscreen mode
Why does «Error: cannot find module» occur?
The error «cannot find module» might happen if you’re trying to:
- Import a third-party package you haven’t installed yet (with
npm
oryarn
). - Import a local module, but the path is wrong.
- Run a node script in the terminal, but the script doesn’t exist (or path is wrong).
- Use node standard libraries with TypeScript, but you haven’t installed the
@types/node
package. - The module’s
package.json
has a main field pointing to an entry file that doesn’t exist.
Before anything, let’s review what a module is and how module systems work in a high level (Or jump to the solutions).
The module system: Modules are the building blocks of an application. Node implements ESM and CommonJS (the default one) module systems to let you organize your code as reusable components.
With modules, you can only expose the public interface of your components and keep the internal functionalities private. This is done by using a module.exports
(CommonJS modules) or export
(ES Modules).
The following code is an example of a module, which has a function to determine whether a number is odd or not:
// math.js
function isOdd(number) {
return number % 2 !== 0
}
// Make isOdd available to other scripts (and other modules)
module.exports = isOdd
Enter fullscreen mode
Exit fullscreen mode
And here’s how we import it into another script called index.js
:
// index.js
const add = require('./isodd.js')
console.log(isOdd(3))
// output: true
Enter fullscreen mode
Exit fullscreen mode
All the modules you use have an ESM or CommonJS export declaration.
How do module systems find modules?
If the identifier passed to require()
or import()
is a reference to a file (it starts with /
, ../
, ./
, etc.) in your filesystem, Node will load it from the respective path. Otherwise, it looks it up in the installed modules — inside the node_modules
directory.
If the module isn’t found, it raises the «Cannot find module» error.
How to fix the «Cannot find module» error in Node.js?
There are several scenarios this error can happen; Let’s explore each.
Third-party packages: If you try to import a third-party module and get this error (and you’re sure the spelling is correct), you probably haven’t installed the package yet.
Imagine this is the code:
//index.js
const axios = require('axios');
// Make an HTTP request with Axios
Enter fullscreen mode
Exit fullscreen mode
If I run this on my machine, I’ll get the «Cannot find module» error.
And that’s because I haven’t installed it yet. So in my project directory (where my package.json
resides), I’d have to install axios
package with npm
or yarn
like so:
npm install axios
Enter fullscreen mode
Exit fullscreen mode
Local modules: Imagine you have a set of utility functions kept in a JavaScript file named utils.js
. You want to import a function called getUrl()
from this utils.js
into your script:
// index.js
const { getUrl } = require('utils')
// Do something here ...
Enter fullscreen mode
Exit fullscreen mode
But when you run npm run build
, the build fails:
ERROR in ./app/index.js 30:0-30
Module not found: Error: Can't resolve 'utils' in '/var/www/app'
Enter fullscreen mode
Exit fullscreen mode
In this case, since utils
isn’t a reference to a local file, my bundler (Webpack) assumes it’s inside a node_modules
directory. The build fails as the utils module isn’t an installed package.
So what I need to do here is to make it an absolute path by adding ./
to my identifier:
// index.js
const { getUrl } = require('./utils.js')
// Do something here ...
Enter fullscreen mode
Exit fullscreen mode
Problem solved.
Sometimes the error occurs because the letter casing is off. File names on Mac and Windows are case-insensitive by default; This means ./Utils
and ./utils
both work on Mac and Windows (where you develop the app). However, it’ll break on a Linux file system where filenames are case-sensitive.
Running a node script: Another scenario reported by developers is when you run a script with the node command. However, the respective file can’t be located — probably owing to a typo in the name or path.
So always double-check that the path is correct and the script exists. You can always take advantage of the terminal’s autocomplete feature by typing the initial letters and pressing the tab to let it complete the path for you.
node ./scriptName.js
Enter fullscreen mode
Exit fullscreen mode
Node and TypeScript: If you’re coding in TypeScript and you’re importing a built-in Node module like fs
, you might get a «Cannot find module ‘fs'» error too.
You can fix the issue by installing @types/node
:
npm install @types/node --save-dev
Enter fullscreen mode
Exit fullscreen mode
Even though all packages in node_modules/@types
(of any enclosing folder) are included in your compilation. However, it’s worth ensuring node is added under compileOptions.types
:
tsconfig.json
{
compilerOptions: {
types: [node, jest, express]
}
}
Enter fullscreen mode
Exit fullscreen mode
Missing entry file in package.json: Each module has an entry file named index.js
(by default) unless it’s changed in the module’s package.json
via the main
field.
{
name: utils
}
Enter fullscreen mode
Exit fullscreen mode
If you decide to change the main
field to another entry file (e.g., main.js
), you must ensure the file exists. Or if you rename or relocate that file in the future, remember to update the package.json
too.
Missing entry file in package.json
has been reported by several users on Stackoverflow.
Importing a module from the global node_modules
or a separate directory: Sometimes you might have to use a globally-installed package in your development environment.
If you try to load a globally-installed module in your project, you might get the «Cannot find module» error.
A workaround to this problem is using the npm link
command. If the package is installed globally, all you need to do is run the following command while in your project directory:
npm link package-name
As a result, npm will create a symbolic link from the globally installed package name to the node_modules
directory of your project — as if you’ve installed it with npm install package-name
.
If the module you want to use is a local file residing somewhere in your file system other than the global node_modules
(e.g., a module you’re developing), you’ll have to do it in a two-step process:
First step: In the terminal, you need to change the directory to where the module resides and run the npm link
(without any parameter). As a result, a symlink is created in the global node_modules that links to your local package.
npm link
Enter fullscreen mode
Exit fullscreen mode
Second step: After that, you change the directory to your project directory (where you want to import the module) and run the following command:
npm link package-name
Enter fullscreen mode
Exit fullscreen mode
This will create a symbolic link from the globally installed package name to the node_modules
directory of your project.
Now, you can use the package as if it’s an installed third-party package.
What if the problem persists?
If none of the above solutions worked for you, maybe you’re dealing with corrupted or incomplete installations. In that case, you can take the following steps:
Delete node_module
directory:
rm -rf node_modules
Enter fullscreen mode
Exit fullscreen mode
Delete package-lock.json
:
rm -f package-lock.json
Enter fullscreen mode
Exit fullscreen mode
Clear the npm cache:
npm cache clean --force
Enter fullscreen mode
Exit fullscreen mode
Install the packages again:
npm install
Enter fullscreen mode
Exit fullscreen mode
This will make a clean install of all the dependencies listed in your package.json
file.
I hope these solutions help you fix your code.
Thanks for reading.
❤️ You might like:
- TypeError: map is not a function in JavaScript in JavaScript (Fixed)
- Add commas to numbers in JavaScript (Explained with examples)
- SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
- How to fix «ReferenceError: document is not defined» in JavaScript
- Label htmlFor Property Explained
JavaScript’s Node.js server supports module export and import in both ECMAScript modules and CommonJS format.
Sometimes, npm will throw an error saying Cannot find module
because of module import as shown below:
$ node index.js
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'axios'
Require stack:
- /n-app/index.js
at ... {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/n-app/index.js' ]
}
Here’s the content of the index.js
file:
var axios = require("axios");
The cannot find module error occurs because npm cannot find the module required by the index.js
file. In this case, the axios
module.
To resolve the error, you need to make sure that axios
is installed in the node_modules/
folder.
Please note that the node_modules/
folder must be located in the same directory as the index.js
file:
.
├── index.js
├── node_modules
├── package-lock.json
└── package.json
If you have run the npm install
command before, then it’s possible that the installation of the module is incomplete or corrupted.
Delete the node_modules/
folder using the rm -rf node_modules
command, then run npm install
again. That may fix the issue.
Finally, the same error can happen when you require()
a local .js
file that can’t be found.
Suppose you have a file named lib.js
placed in the same folder as the index.js
file:
.
├── index.js
└── lib.js
To import the file, you need to specify the correct path in the require()
function.
The following code:
var helper = require("lib.js");
Will produce the same error:
$ node index.js
node:internal/modules/cjs/loader:936
throw err;
^
Error: Cannot find module 'lib.js'
Require stack:
- /n-app/index.js
at ... {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/n-app/index.js' ]
}
This is because the require()
function will always look inside the node_modules/
folder.
To let Node.js knows that you are importing a local file, use the absolute path as follows:
The ./
syntax means the root directory where you run the node
command. In this case, the folder where index.js
is located.
If you have a file one level down like this:
.
├── index.js
└── helpers
└── lib.js
Then you need to adjust the require()
path as shown below:
var helper = require("./helpers/lib.js");
The same also applies when you use the ES modules format as follows:
import helper from "./helpers/lib.mjs";
To conclude, the error “Cannot find module” happens when Node.js can’t find the module that a file is trying to import.
You can see the file and the module that’s causing the issue from the error output generated by Node itself.
And that’s how you resolve the npm cannot find module issue. Great work! 😉
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.