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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14264429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:12:46  来源:igfitidea点击:

how to use jQuery installed with npm in Express app?

javascriptjquerynode.jsexpress

提问by ilyo

I have a node.js + express app and I installed jQuery with npm.

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

in the app.jsfile I used

app.js我使用的文件中

var jquery = require('jquery');

In the html file header I included javascript that uses jQuery and I get `jQuery is not defined'. Is it a metter of order or am I missing something?

在 html 文件头中,我包含了使用 jQuery 的 javascript,但我得到“未定义 jQuery”。这是一米的秩序还是我错过了什么?

采纳答案by Jean-Philippe Bond

When you are installing jQuerywith npmit's because you want to use jQueryon the server side of your application (Ex : in your app.jsfile). You still need to add jQueryto your web page like that :

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

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

If you want to use it on the client side. If you are using Jade, add the script tag to your template.

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

回答by Lukasz Wiktor

If you want a jquery npm module to be served by an express app then add this line to the server script (in your case app.js):

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

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

After that you can include it in your html file:

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

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

回答by IT Vlogs

Way to use jquery from npm:

从 npm 使用 jquery 的方法:

In app.js

在 app.js 中

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

In layout template:

在布局模板中:

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

hope this code help you!

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

回答by Costas Develop

I'm using express 4.10.2. and I followed Lukasz Wiktor answer but it didn't work for me. I had to alter Lukasz solution a little bit:

我正在使用快递 4.10.2。我跟着 Lukasz Wiktor 回答,但这对我不起作用。我不得不稍微改变 Lukasz 解决方案:

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

in the html file I also included:

在 html 文件中,我还包括:

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

So /jquery is the mounting point of the /node_modules/jquery/dist/ directory.

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