Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 399
ilyo Avatar asked Jan 10 '13 18:01

ilyo


People also ask

Can I use jquery in Nodejs?

js: We can use jQuery in Node. js using the jquery module. Note: Use the 'jquery' module not the 'jQuery' module as the latter is deprecated.

What is jquery NPM?

The name npm (Node Package Manager) stems from when npm first was created as a package manager for Node. js. All npm packages are defined in files called package.

What is express NPM package?

Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid development of Node based Web applications.


2 Answers

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> 
like image 164
Lukasz Wiktor Avatar answered Sep 29 '22 13:09

Lukasz Wiktor


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.

like image 23
Jean-Philippe Bond Avatar answered Sep 29 '22 12:09

Jean-Philippe Bond