【问题标题】:how to use jQuery installed with npm in Express app?如何在 Express 应用程序中使用与 npm 一起安装的 jQuery?
【发布时间】:2012-12-25 05:23:16
【问题描述】:

我有一个 node.js + express 应用程序,我用 npm 安装了 jQuery。

在我使用的app.js 文件中

var jquery = require('jquery');

在 html 文件头中,我包含了使用 jQuery 的 javascript,但我得到了“未定义 jQuery”。 是秩序井然还是我遗漏了什么?

【问题讨论】:

  • 你说的是哪个标题?你能发布你的javascript代码吗?
  • 主要问题是你为什么要使用 jQuery 和 node?它运行大量为旧 JavaScript 规范设计的代码,以兼容浏览器。这可能很有趣:Reduction of CPU utilization on a nodejs server 在服务器端你可以用 jQuery 做大部分事情,例如Cloning an Object in Node.js,你也可以用 Underscore 做。
  • @esp 我不明白的是服务器和客户端使用不同的 jQuery 文件,我认为使用 NPM 安装它会给我在客户端的 jQuery

标签: javascript jquery node.js express


【解决方案1】:

当您使用npm 安装jQuery 时,这是因为您想在应用程序的服务器端使用jQuery(例如:在您的app.js 文件中)。您仍然需要像这样将jQuery 添加到您的网页:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

如果你想在客户端使用它。如果您使用的是Jade,请将脚本标签添加到您的模板中。

【讨论】:

  • Jean,为什么要在服务器端使用 jquery?
  • @GovindRai 用于生成 HTML,在字符串中操作 DOM 等。如果您想了解更多信息,请查看这个库,它是服务器端的 JQuery 实现:github.com/cheeriojs/cheerio
【解决方案2】:

如果您希望 jquery npm 模块由 express 应用程序提供服务,则将此行添加到服务器脚本(在您的情况下为 app.js):

app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/'));

之后,您可以将其包含在您的 html 文件中:

<script src="/jquery/jquery.js"></script>

【讨论】:

  • 应该是app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/'));否则是404
  • 谢谢!接受的答案很奇怪。或者npm install serve-static 然后var serveStatic = require('serve-static')app.use(serveStatic('node_modules...'))
  • 太棒了!虽然我建议使用 path.join(__dirname, 'node_modules', 'jquery', 'dist') 以便它与特定于平台的分隔符一起使用,但请查看详细说明:stackoverflow.com/questions/9756567/…
【解决方案3】:

我使用的是 express 4.10.2。我跟着 Lukasz Wiktor 回答,但它对我不起作用。我不得不稍微改变一下 Lukasz 的解决方案:

app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/'));

在 html 文件中我还包括:

<script src="/jquery/jquery.js"></script>

所以 /jquery 是 /node_modules/jquery/dist/ 目录的挂载点。

【讨论】:

    【解决方案4】:

    在 npm 中使用 jquery 的方法:

    在 app.js 中

    app.use('/assets', [
        express.static(__dirname + '/node_modules/jquery/dist/'),
        express.static(__dirname + '/node_modules/materialize-css/dist/'),
        ...
    ]);
    

    在布局模板中:

    <script src="/assets/jquery.min.js"></script>
    <script src="/assets/js/materialize.min.js"></script>
    

    希望此代码对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-09
      • 2019-02-23
      • 2020-02-15
      • 2014-05-30
      • 2022-01-02
      • 1970-01-01
      • 2019-03-19
      • 2011-08-20
      相关资源
      最近更新 更多