【问题标题】:Cannot call module's function after browserifybrowserify 后无法调用模块的函数
【发布时间】: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


【解决方案1】:

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

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

编辑

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>

【讨论】:

  • 我不明白如何从 html/embedded js 访问 test.js 中定义的函数(当它被浏览器化时)的主要问题。
  • 啊哈!在最初的问题中并不清楚从嵌入代码中调用它的需要。我编辑了答案,可以通过将您的功能附加到窗口范围来完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2015-10-13
  • 1970-01-01
相关资源
最近更新 更多