browserify 后无法调用模块的功能

Cannot call module's function after browserify

我正在尝试使用 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) 正常工作吗?

您需要将所有包含来自 Node 的任何内容的 JavaScript 代码放入 test.js 文件中,然后您将使用 browserify 将其转换为 te bundle.js。在您的示例中,您在 index.html 中使用了节点函数 require,它不会被转换。浏览器然后看到他不知道的函数require(),这就是隐藏问题的地方。

简单地说:您的所有 javascript 代码(包含 Node)必须作为单个 bundle.js 包含在您的 index.html 中,这是来自您的源文件的浏览器化结果。

编辑

Browserify(默认情况下)不允许您从浏览器化代码中调用任何浏览器化函数。但是您可以通过将函数附加到 window 范围来使其可用。

这是 test.js(然后由 browserify 转换为 bundle.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>