Uncaught ReferenceError: require is not defined

etherethers.jsjavascriptweb3js

I am fairly new to Ethereum development, I just tried to follow this tutorial but instead of connection to a public blockchain I am trying to connect to my local blockchain instance through MetaMask which is already installed and the local chain is added to it. However, I am facing an issue at the first line of my code during the "require" part. Here is my code below:

const { ethers } = require("ethers");
const provider = new ethers.providers.Web3Provider(window.ethereum)
async function connectToMetamask(){
   await provider.send("eth_requestAccounts", []);
}
connectToMetamask();
const signer = provider.getSigner();

const ERC20_ABI = [
   "function getAll() public view returns(uint [] memory)",
   "function get(uint position) public view returns(uint)",
   "function add(uint id, string memory activityName, string memory authorName, string memory activityType) public",
   "function length() public view returns(uint)",
]

const address = '0xf0c707dafa300d8bd19bbfed42b86469d50b022f';

const contractInstance = new ethers.Contract(address, ERC20_ABI, provider);

const main = async () => {
   const name = await contractInstance.name();
   console.log("name: " , name);
}

main();

And the error I am facing is below:

Uncaught ReferenceError: require is not defined at code.js:1:20

Can anyone help me with solving this issue? I followed this tutorial step-by-step but doesn't seem to work for me..

Note: I have already written my own contract and deployed it to my local blockchain and that is where I got all these functions and the address from.

Best Answer

So after searching for a while through the internet I found what the issue was and how to solve it.

The Issue:

I was trying to run a Node JS code within my browser (which apparently doesn't work, especially if you're using 'require' keyword).

The Solution:

To solve this I had to use browserify.

What browserify does apparently is wrapping your js code into a new js file that can be run within the browser. The usage could be a little confusing, especially for Windows users since after installing browserify in windows the keyword 'browserify' doesn't get recognized in CMD. So here are the steps I did to make my code work:

  • Install browserify by using npm install -g browserify command
  • Navigate to my project's folder with CMD
  • Run this command node .\node_modules\browserify\bin\cmd.js code.js -o bundle.js instead of browserify code.js -o bundle.js because... well Windows. (Note that the "code.js" should be replaced with the name of your js file)
  • Finally included the newly generated bundle.js file instead of my code.js in my html file <script src="bundle.js"></script> and my code finally ran fine.

Hope this answers this question to anyone else after me and they won't have to look for days to find this simple answer.

Related Topic