我正在尝试用JS模块制作简单的页面,这将对页面做一些事情。我需要使用node.js的模块,所以我正在学习如何浏览工作。
我的HTML:
<!doctype html>
<html>
<head>
<script src="js/bundle.js" type="text/javascript"></script>
</head>
<body>
<p>Hello world!</p>
<script type="text/javascript">
var test = require("./test.js");
test.init();
</script>
</body>
</html>这是我的JavaScript (test.js):
"use strict";
alert("here1");
var init = function() {
alert("here2");
}
exports.init = init我正在用:
browserify.cmd test.js -o bundle.js当我试图打开页面时,它显示"here1“,但不显示"here2”。在浏览器的控制台中,我看到:
Uncaught ReferenceError: require is not defined index.html:9如何使模块的功能(init)正常工作?
发布于 2016-04-08 23:03:54
您需要将包含Node的所有JavaScript代码放在test.js文件中,然后使用浏览器将其转换为te bundle.js。在您的示例中,您使用的是index.html中的Node函数index.html,它不会被转换。然后浏览器会看到他不知道的函数require(),这就是隐藏问题的地方。
简单地告诉您:所有的javascript代码(包含Node)都必须作为一个单独的bundle.js包含在您的bundle.js中,这是源文件中的一个浏览结果。
编辑
Browserify (默认情况下)不允许在浏览器序列化代码之外调用任何浏览器序列化函数。但是,您可以通过将函数附加到window作用域来使其可用。
这是test.js (然后通过浏览器化将其转换为)和index.html
"use strict";
alert("here1");
window.init = function() {
alert("here2");
}<!doctype html>
<html>
<head>
<script src="js/bundle.js" type="text/javascript"></script>
</head>
<body>
<p>Hello world!</p>
<script type="text/javascript">
init();
</script>
</body>
</html>
https://stackoverflow.com/questions/36510404
复制相似问题