Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using browserify, Uncaught ReferenceError: function is not defined

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!

like image 553
Yu Liu Avatar asked May 29 '15 06:05

Yu Liu


People also ask

What is Browserify in node JS?

Browserify is an open-source JavaScript bundler tool that allows developers to write and use Node. js-style modules that compile for use in the browser.

What is uncaught ReferenceError in JavaScript?

The Javascript ReferenceError occurs when referencing a variable that does not exist or has not yet been initialized in the current scope.

How do I Browserify users?

Usage: browserify [entry files] {OPTIONS} Standard Options: --outfile, -o Write the browserify bundle to this file. If unspecified, browserify prints to stdout. --require, -r A module name or file to bundle. require() Optionally use a colon separator to set the target.

What are some of the benefits of Browserify?

Browserify provides a common way to structure all of your JavaScript code by bundling dependencies into a single file that can be referenced within a <script> tag in the browser.


1 Answers

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.

like image 53
cchamberlain Avatar answered Oct 04 '22 15:10

cchamberlain