When I use a bundler to make my JS browser compatible my exported functions are not exported.
Error: (index):11 Uncaught TypeError: connect is not a function at HTMLButtonElement.onclick ((index):11:46)
index.js (Same root file as index.html)
const {ethers} = require("ethers");
async function connect() {
if (typeof window.ethereum !== 'undefined') {
await ethereum.request({method: "eth_requestAccounts"});
}
}
module.exports = {
connect
}
index.html (Same root file as index.js)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>HTML 5 Boilerplate</title>
<script src="./index.js" type="module"></script>
</head>
<body>
<button id="connect" onclick="connect()"> Connect </button>
</body>
</html>
Using parcel, which auto creates a dist file and starts a local server. Also tried browserify and had same issue.
Parcel supports script tag/elements of type module.
This code works for me but window.ethereum is undefined, it's related to MetaMask no?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>HTML 5 Boilerplate</title>
</head>
<body>
<button id="connect">Connect</button>
<script type="module">
//Import your module
import something from "./index.js";
//Assign event listener to button
document
.getElementById("connect")
.addEventListener("click", function (event) {
something.connect();
});
console.log("something", something);
/* JavaScript module code here */
</script>
</body>
</html>
const { ethers } = require("ethers");
async function connect() {
console.log("Inside connect function");
console.log("window.etherum", window.ethereum);
console.log("ethers", ethers);
if (typeof window.ethereum !== "undefined") {
await ethereum.request({ method: "eth_requestAccounts" });
}
}
module.exports = {
connect,
};