在HTML中使用Node.js模块

8
我有一个Node.js项目(这是我的问题的最小工作示例):

module1.js:

module.exports = function() {
    return "this is module1!";
};

module2.js:

var module1 = require('./module1');
module.exports = function() {
    return module1()+" and this is module2!";
};

server.js:

var module2 = require('./module2');
console.log(module2());  // prints: "this is module1! and this is module2!"

现在我想创建一个名为client.html的文件,它也将使用module2.js。这是我尝试过但失败了的代码:

naive version:

<script src='module2.js'></script>
<script>alert(module2());</script> // should alert: "this is module1! and this is module2!"

这显然不起作用 - 它会产生两个错误:

  • 引用错误:require未定义。
  • 引用错误:module2未定义。

使用Node-Browserify 运行后:

browserify module2.js > module2.browserified.js

我将client.html更改为:

<script src='require.js'></script>
<script>
    var module2 = require('module2');
    alert(module2());
</script>

这个不起作用 - 它会产生一个错误:

  • ReferenceError: module2未定义。

使用Smoothie.js by @Torben:

<script src='require.js'></script>
<script>
    var module2 = require('module2');
    alert(module2());
</script>

这不起作用 - 它会产生三个错误:

  • module2.js第1行语法错误。
  • SmoothieError:无法加载模块2(0)
  • TypeError:module2不是一个函数

我看了require.js,但它似乎太复杂了,无法与Node.js结合使用 - 我没有找到一个简单的例子,可以将现有的Node.js模块加载到网页中(就像在示例中一样)。

我看了head.jslab.js,但没有提到Node.js的require。

那么,我应该怎么做才能从HTML页面中使用我的现有Node.js模块module2.js?


据我所知,您无法从HTML页面调用节点模块。为此,您需要使用模板库将数据从server.js传递到HTML页面。 - umair
@umair 我不需要client.html页面与server.js程序联系 - 它们是两个独立的应用程序。 - Erel Segal-Halevi
然后将它们编写为JavaScript函数,而不是Node模块,并将脚本包含在您的HTML中。 - umair
你是否在服务器日志中验证了你的require('module2')是否找到了你期望找到的文件?比如说,这个文件是否公开可用? - juanpaco
@juanpaco server.js程序运行良好 - 它打印字符串“this is module1! and this is module2!”,这意味着它正确找到了两个模块。问题出在client.html上。 - Erel Segal-Halevi
显示剩余3条评论
3个回答

8
问题在于你正在使用CJS模块,但仍然尝试以内联脚本的旧方式进行操作。这样是行不通的,只能选择其中之一。
为了充分利用CJS风格,请按照与服务器端完全相同的方式组织客户端代码,因此:
创建client.js:
var module2 = require('./module2');
console.log(module2());  // prints: "this is module1! and this is module2!"

使用Browserify(或其他您选择的CommonJS打包工具)创建捆绑包:
browserify client.js > client.bundle.js

在HTML中包含生成的捆绑文件:
<script src="client.bundle.js"></script>

页面加载完成后,您应该在浏览器控制台中看到"this is module1! and this is module2!"


1
您也可以尝试使用simq,我可以帮助您。

谢谢!我不使用simq的原因是它需要一个配置文件,而我的需求更简单,可以在没有配置文件的情况下解决。 - Erel Segal-Halevi
虽然这理论上回答了问题,但最好在此处包含答案的基本部分,并提供参考链接。 - SuperBiasedMan

1
你在使用Smoothie Require遇到的问题是由一个bug引起的(https://github.com/letorbi/smoothie/issues/3)。我的最新提交修复了这个bug,所以你的示例现在应该可以正常工作,无需任何更改。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接