14

I am trying example in http://browserify.org/ and try to make a function call as follows:

My html is:

<!DOCTYPE html>
<html>
<head>
<title>Test Browserify</title>

<script src="bundle.js"></script>

</head>
<body>
  <button onclick="hello()">test</button>
 </body>
</html>

and my javascript is:

var unique = require('uniq');

var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];

console.log(unique(data));

function hello(){
    alert("here");
}

I did browserify main.js -o bundle.js, so I can use require successfully.

But when I click the button, I have the error:

"Uncaught ReferenceError: hello is not defined"

Any suggestion will be appreciated!

cchamberlain
  • 17,444
  • 7
  • 59
  • 72
Yu Liu
  • 171
  • 1
  • 3

2 Answers2

14

Browserifies primary purpose is to make JavaScript modules privately scoped so it has no way to see what you are trying to do.

Try using

global.hello = function() { alert("hello");}

See defining global variable for browserify.

In general, this is bad practice and you should instead export public properties out of your module and reference them via the required module reference.

Community
  • 1
  • 1
cchamberlain
  • 17,444
  • 7
  • 59
  • 72
  • I did try exporting my function but could not figure out how to import it correctly into my html file. I exported from main.js like this: `module.exports.beep = function (n) { return n * 1000 }`. I tried importing into my index.html like this: ``. I ran browserify like this: `browserify src/main.js -o public/bundle.js`. However I got "Uncaught ReferenceError: beep is not defined" when I tried to load index.html in browser. Using your `global.hello` approach worked! But I would love to use module reference if possible. – Michael Osofsky Jul 17 '21 at 00:06
  • Do you mean/trying to say that _**During the bundling process Browserify puts the code that we think is in global scope in a new module on its own, so that's why it can't access the globals**_?? – Lyubomir Dec 28 '22 at 09:01
2

just try to use global.hello = function() { alert("hello");} in your js file and then build it using browserify.