'Cannot find module web3

I simply am trying to import web3 to my project and for whatever reason I cannot seem to resolve the issue I am facing. The relevant code is posted below:

Example.js

const Web3 = require('web3');
console.log('hi');

Package.json

{
  "name": "inbox",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "ganache-cli": "^6.12.2",
    "mocha": "^9.1.2",
    "solc": "^0.4.17",
    "web3": "^1.7.2"
  }
}

I'll get the preliminary questions out of the way:

  • Yes, I have run "npm install web3"
  • Yes, I have tried deleting the node_modules folder and package-lock.json file and re-running "npm install"
  • Yes, I have tried switching to running "npm install ethereum/web3.js"

When running "node Example.js", I get the following error:

Error: Cannot find module '/Users/username/project/node_modules/web3/lib/index.js

After looking through my node_modules folder, I found that the actual path to the index.js file of the web3 folder is: /Users/username/project/node_modules/web3/src/index.js

I am unsure why node is looking for a 'lib' folder when all the web3 packages in node_modules have 'src' folders. In case anyone is wondering, I am running npm v8.6.0 and node v16.14.2 (also tried with node v14.17.2 and got same errors).



Solution 1:[1]

When you see this error message, usually means your web3 installation was failed/uncompleted. the path node_modules/web3/lib/ exists in successful installation.

I guess some tools are missing in your environment.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 juagicre