JDS
JDS

Reputation: 16978

How to add this library (web3) and use on my html page?

I have a node project where I am trying to use web3 on a simple html page so users can write something to a simple smart contract. Step 1 I am trying is simply to have access to the web3 object in a JavaScript file called by main.html.

Here is the folder structure:

index.js
package.json
main.html (uses main.js)
assets/
    js/
        main.js

The following code I use to get started with ganache test network on my computer:

const Web3 = require('web3');
const web3 = new Web3 ( "http://localhost:7545" )
const ethEnabled = async () => {
  if (window.ethereum) {
    await window.ethereum.send('eth_requestAccounts');
    window.web3 = new Web3(window.ethereum);
    console.log("Connected to web3");
    return true;
    
  }
  alert("Error - could not connect via web3.js");
  return false;

}

However when I paste this code to the top of assets/js/main.js I get the following:

Uncaught ReferenceError: require is not defined at main.js:5

So I can't even use the require package, let alone the web3 package, both of which I have both installed via npm install.

However, when I paste the above web3 code in index.js it doesn't seem to give an error:

const express = require('express')
const app = express()
const port = 3000

const Web3 = require('web3');
const web3 = new Web3 ( "http://localhost:7545" )
const ethEnabled = async () => {
  if (window.ethereum) {
    await window.ethereum.send('eth_requestAccounts');
    window.web3 = new Web3(window.ethereum);
    console.log("Connected to web3");
    return true;
    
  }
  alert("Error - could not connect via web3.js");
  return false;

}

app.use(express.static("./assets"));

app.get('/', (req, res) => {
  //res.send('Hello World!')
  res.sendFile('./main.html', { root: __dirname });
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

I want to use web3 functionality on main.html with main.js, as the user would be filling out a form, hitting a button, then I'd use web3 functionality to write something to my simple contract.

But I think I am not understanding node.js project layout and structure. Given the use case above, how should I proceed? When I put the web3 starter code in index.js, I don't know how to access the web3 object in main.js. How should I do this?

Upvotes: 1

Views: 3787

Answers (1)

D.Pacheco
D.Pacheco

Reputation: 540

You need to use pure js file in your .html. Add the script in your header and only instanciate the Web3 class: new Web3 ( "http://localhost:7545" ),

<script src="https://github.com/ChainSafe/web3.js/blob/v1.2.11/dist/web3.min.js></script>

Upvotes: 1

Related Questions