使用browserify,未定义Uncaught ReferenceError:function

时间:2022-01-05 03:45:31

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

我在http://browserify.org/中尝试示例并尝试按如下方式进行函数调用:

My html is:

我的HTML是:

<!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:

我的javascript是:

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.

我做了browserify main.js -o bundle.js,所以我可以成功使用require。

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

但是当我点击按钮时,我有错误:

"Uncaught ReferenceError: hello is not defined"

“未捕获的ReferenceError:未定义hello”

Any suggestion will be appreciated!

任何建议将不胜感激!

1 个解决方案

#1


8  

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

浏览器的主要目的是使JavaScript模块具有私有范围,因此无法查看您要执行的操作。

Try using

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

See defining global variable for browserify.

请参阅为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.

一般来说,这是不好的做法,您应该从模块中导出公共属性,并通过所需的模块引用引用它们。

#1


8  

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

浏览器的主要目的是使JavaScript模块具有私有范围,因此无法查看您要执行的操作。

Try using

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

See defining global variable for browserify.

请参阅为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.

一般来说,这是不好的做法,您应该从模块中导出公共属性,并通过所需的模块引用引用它们。