我在http://browserify.org/中尝试示例并尝试按如下方式进行函数调用:
我的HTML是:
<!DOCTYPE html>
<html>
<head>
<title>Test Browserify</title>
<script src="bundle.js"></script>
</head>
<body>
<button onclick="hello()">test</button>
</body>
</html>
我的javascript是:
var unique = require('uniq');
var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];
console.log(unique(data));
function hello(){
alert("here");
}
我确实浏览了main.js -o bundle.js,所以我可以成功使用require。
但是当我点击按钮时,我有错误:
“未捕获的ReferenceError:未定义hello”
任何建议都将不胜感激!
答案 0 :(得分:8)
浏览器的主要目的是使JavaScript模块具有私有范围,因此无法查看您要执行的操作。
尝试使用
global.hello = function() { alert("hello");}
请参阅defining global variable for browserify。
通常,这是不好的做法,您应该将公共属性从模块中导出,并通过所需的模块引用引用它们。
答案 1 :(得分:1)
只需尝试在您的js文件中使用global.hello = function() { alert("hello");}
,然后使用 browserify 进行构建即可。