Arthur Isnt original
Arthur Isnt original

Reputation: 125

function is not defined, when it is

today i was working on a project, and i got this error.

Uncaught ReferenceError: launch is not defined at HTMLInputElement.onclick (home.html:77)

i don't understand what i did wrong here.. Here is the index.js file:

function launch() {
  console.log('test');
}
  

module.exports.launch = launch;

and home.html:

<script>
    let func  = require('./index');

    let launch = func.launch();

    document.getElementById('lanBTN').addEventListener('click', () => {
      launch();
    });

   <input type="button" value="Launch!" id="lanBTN" onclick="launch()">
  </script> 

Any ideas why this is happening..?

Upvotes: 0

Views: 1153

Answers (2)

Kavian Rabbani
Kavian Rabbani

Reputation: 984

As @mehdi-belbal mentioned you can not use CommonJS in HTML files expect if when using module bundlers like Webpack.
Besides of that module.exports is useless here, try to link your javascript module in the head of the document. and the declared function after. that will attach to the window object and you can use them both by using window.func() and ‍func()

<head>
  <script src="./index.js"></script>
</head>
<body>
  ...
  <script>
    func();
  </script>
</body>

Upvotes: 0

Mehdi Belbal
Mehdi Belbal

Reputation: 553

Require is a commonjs module specification, it doesn't work on the browser unless you use some bundler like webpack or browserify to resolve the dependencies between all of you modules and bundles one single js file to include in your html

Upvotes: 1

Related Questions