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!

1
  • I'm guessing that you are seeing your 1, 2, 3, 4, ,5, 6 getting printed at the js console? Commented May 29, 2015 at 7:02

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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: <script src="bundle.js"></script>. 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.
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??
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.