0

I've been confused by the web3.js all day.

I created the web.js for setting and initialize Web3, and it appears the following message:

enter image description here

And I install web3 by npm install web3, the version of web3 is 1.5.2 the version of node.js is 14.17.0, the npm is 6.14.13.

should I import the web3.min.js or I just miss something essential?

the code of web3.js shown below:

// Initialize Web3
var Web3 = require("web3"); << where the error is
var web3 = new Web3("https://localhost:8545");

// Set Account
web3.eth.defaultAccount = 'xxx';

// Set Contract Abi
var ABI = [abi];

// Set Contract Address
var contractAddress = 'xxx';

// Set the Contract
var contract = new web3.eth.Contract(ABI, contractAddress);
3
  • Are you using raw html or some framework like react or angular? For raw html use web3.min.js.
    – Ismael
    Sep 16 at 4:53
  • which means if I just use html and js, I've better install the web3 by npm right?
    – ginwei
    Sep 16 at 7:39
  • Running npm install only applies to a project managed by npm. If your project is a pure html and js files without a build tool like webpack, or browserify then you have to use web3.min.js. If you use a build tool then check the documentation, but npm install web3 works in most cases.
    – Ismael
    Sep 16 at 15:01
1

I find out where the problem is.

I should introduce the js file in html by following order:

<script src="web3.min.js"></script>
<script src="web3.js"></script>
<script src="htmlfile.js"></script>

Although I've cleaned up the error, I find out that contract.methods didn't work. I think that should be another problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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