如何在Express应用程序中使用npm安装的jQuery?

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

在我使用的app.js文件中

 var jquery = require('jquery'); 

在html文件头我包括JavaScript使用jQuery,我得到`jQuery没有定义'。 这是秩序吗?还是我错过了什么?

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

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 

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

如果你想要一个jQuery的npm模块由一个快速的应用程序服务,然后将此行添加到服务器脚本(在你的情况下app.js ):

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

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

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

我使用Express 4.10.2。 我遵循了Lukasz Wiktor的回答,但这对我没有任何作用。 我必须稍微改变Lukasz解决scheme:

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

在html文件中我还包括:

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

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