在HTML中使用Node.js模块

埃雷尔·塞加尔·哈利维(Erel Segal-Halevi)

我有以下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!"

现在,我想创建一个也将使用module2.jsclient.html文件。这是我尝试过的(但失败了):

天真的版本

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

这显然行不通-产生两个错误:

  • ReferenceError:未定义require。
  • ReferenceError:未定义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。

使用@Torben的Smoothie.js

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

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

  • module2.js第1行的语法错误
  • SmoothieError:无法加载module2(0)
  • TypeError:module2不是函数

我查看了require.js,但与Node.js组合起来看起来太复杂了-我没有找到一个简单的示例,该示例仅采用现有的Node.js模块并将其加载到网页中(如示例中所示)。

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

因此,为了从HTML页面使用现有的Node.js模块module2.js,我应该怎么做?

马里乌斯·诺瓦克(Mariusz Nowak)

问题是您正在使用CJS模块,但仍尝试使用内联脚本进行旧方法。那是行不通的,要么就是这个,就是那个。

要充分利用CJS样式,请完全按照与服务器端相同的方式来组织客户端代码,因此:

创建client.js:

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

使用Browserify(或您选择的其他CJS捆绑器)创建捆绑包:

browserify client.js > client.bundle.js

在HTML中包括生成的包:

<script src="client.bundle.js"></script>

页面加载后,您应该看到“这是module1 !,这是module2!”。在浏览器控制台中

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章