how to use jQuery installed with npm in Express app?


Question

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?

1
30
8/1/2014 7:52:25 AM

Accepted Answer

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="//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.

23
8/9/2013 8:29:35 PM

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>

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon