8

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

模块1.js

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

模块2.js

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

服务器.js

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

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

天真的版本

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

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

  • ReferenceError: 要求未定义。
  • 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: 无法加载模块 2 (0)
  • 类型错误:module2 不是函数

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

我查看了head.jslab.js,但没有发现 Node.js 的要求。

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

4

3 回答 3

8

问题是您正在使用 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>

加载页面后,您应该看到“这是模块 1!这是模块 2!” 在浏览器控制台中

于 2014-01-27T20:07:06.647 回答
1

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

于 2014-01-27T15:41:45.450 回答
1

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

于 2014-01-28T17:21:12.917 回答