简体   繁体   中英

how to use jQuery installed with npm in Express app?

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

in the app.js file I used

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?

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 ):

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

After that you can include it in your html file:

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

When you are installing jQuery with npm it's because you want to use jQuery on the server side of your application (Ex: in your app.js file). You still need to add jQuery to your web page like that:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/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.

Way to use jquery from npm:

In 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!

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:

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

in the html file I also included:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM