1

I have three js files as below

index.js

function getNumberToDisplay(){
    document.getElementById("currentDay").innerHTML = getNumber();
}

checkDay.js

const randomDate = require("./randomDate");
module.exports = {};
function getNumber(){
    return randomDate.getSmallNumber();
}
module.exports.getNumber = getNumber;

randomDate.js

module.exports = {};
function getSmallNumber(){
    return 3;
}
module.exports.getSmallNumber = getSmallNumber;

I also have a html page which has a button which calls the getNumberToDisplay function. All 3 scripts are included in the html page by using the tags. When I press the button to call getNumberToDisplay I get the error Uncaught ReferenceError: Cannot access 'randomDate' before initialization

What is it that I am missing in order to be able to get the button to execute the function? The tests of the functions return the expected results in Jest, but the button doesn't work when opening the html page in Chrome.

a.cayzer
  • 289
  • 4
  • 22
  • 1
    this is not javascript, it looks more like nodejs. This won't work – Scriptkiddy1337 Dec 31 '21 at 17:44
  • https://stackoverflow.com/questions/7576001/how-can-i-require-commonjs-modules-in-the-browser – HDM91 Dec 31 '21 at 17:46
  • Ah, I have been using Jest to test the code, I have created the above simple code to just replicate the problem. Is there a way to make this work without using server to host the code? Can Chrome handle node natively? – a.cayzer Dec 31 '21 at 19:10

0 Answers0