【发布时间】:2016-07-30 08:31:08
【问题描述】:
我正在尝试使用 JS 模块制作简单的页面,该模块将对页面进行一些操作。我需要使用 node.js 的模块,所以我正在学习如何进行 browserify 工作。
我的 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)正常工作?
【问题讨论】:
-
因为 require 不是原生 js 函数,它应该在你的 test.js 中使用,因为它是 browserify 用来捆绑你的模块的
-
但是我怎样才能从 html/embedded js 访问 test.js 中定义的函数呢?
标签: javascript browserify require