0

My code works but I am getting this with Web3 dotted.

Could not find name 'Web3'. Did you mean 'web3'?

const web3 = new Web3(Web3.givenProvider || infuraUrl);

When I try to fix it by doing this: const web3 = new web3(web3.givenProvider || infuraUrl); I wont get the error but I will get this in Browser console:

app.js:3 Uncaught ReferenceError: Cannot access 'web3' before initialization

My code works with Web3 being in capital, is there any reason to change it. If so why?

1
  • Hi trox! Welcome to Ethereum Stackexchange! How are you importing web3 into your code? Are you following their documentation? In particular the "Getting started" section here docs.web3js.org.
    – Ismael
    Commented Dec 8, 2023 at 13:29

2 Answers 2

1

dev Advocate at Chainstack here!

It looks like that might be an issue with how you are importing the web3.js package.

This is how you import the package and create a web3 instance:

const { Web3 } = require("web3");

const node_url = "CHAINSTACK_NODE_URL";
const web3 = new Web3(node_url);

Now you can use the web3 instance to call RPC methods like this:

const { Web3 } = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);

async function getLatestBlockNumber() {
  const block = await web3.eth.getBlockNumber();
  console.log(`Latest block: ${block}`);
}
  
getLatestBlockNumber()

Those examples are based on web3.js V 4.x

You can find more examples on the Chainstack docs (full disclosure, I made those) or in the official web3.js docs.

0

Depends on how you imported your web3

Const {Web3} = require (‘web3’)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.