【问题标题】:Using Node.js modules in HTML在 HTML 中使用 Node.js 模块
【发布时间】:2014-02-18 02:47:37
【问题描述】:

我有以下 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.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)
  • TypeError: module2 不是函数

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

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

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

【问题讨论】:

  • 据我所知,您不能从 HTML 页面调用您的节点模块。为此,您需要使用模板库将 server.js 中的数据传递到 HTML 页面。
  • @umair 我不需要 client.html 页面来联系 server.js 程序 - 它们是两个独立的应用程序。
  • 然后将它们编写为 javascript 函数而不是节点模块,并将脚本包含在您的 HTML 中
  • 我想在client.html和server.js中都使用同一个模块module2.js,而不需要重复代码。
  • 您是否在服务器日志中确认您的require('module2') 正在查找您希望它找到的文件?比如,该文件是公开的吗?

标签: javascript node.js require smooth browserify


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你也可以试试simq,我可以帮你。

    【讨论】:

    • 谢谢!我不使用simq的原因是它需要配置文件,而我的需求要简单得多,无需配置文件即可解决。
    • 虽然理论上这可以回答这个问题,it would be preferable 在这里包含答案的基本部分,并提供链接以供参考。
    【解决方案3】:

    您的 Smoothie Require 问题是由错误 (https://github.com/letorbi/smoothie/issues/3) 引起的。我最近的提交修复了这个错误,因此您的示例现在应该可以在没有任何更改的情况下工作。

    【讨论】:

      猜你喜欢
      • 2013-02-09
      • 2018-10-16
      • 2012-10-05
      • 2013-04-28
      • 2012-10-09
      • 2020-01-15
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多