how to use jQuery installed with npm in Express app?
Solution 1
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.
Solution 2
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>
Solution 3
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!
Solution 4
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.
ilyo
Updated on January 04, 2021Comments
-
ilyo over 3 years
I have a node.js + express app and I installed jQuery with npm.
in the
app.js
file I usedvar 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?
-
Juan Picado almost 7 yearsIt should be
app.use('/jquery', express.static(__dirname + '/node_modules/jquery/dist/'));
otherwise is 404 -
Govind Rai almost 7 yearsWhy would one use jquery on the server side, Jean?
-
Jean-Philippe Bond almost 7 years@GovindRai For generating HTML, manipulating DOM inside a String, etc.Take a look at this lib if you want to know more, it is a implementation of JQuery for the server side : github.com/cheeriojs/cheerio.
-
v.oddou almost 5 yearsthanks ! the accepted answer is weird. alternatively
npm install serve-static
thenvar serveStatic = require('serve-static')
andapp.use(serveStatic('node_modules...'))
-
Patrick almost 5 yearsGreat! Although I would recommend using
path.join(__dirname, 'node_modules', 'jquery', 'dist')
so that it works with platform specific delimiters, check out for a detailed explanation: stackoverflow.com/questions/9756567/… -
klewis about 2 yearsThank you soooo much for this education and clarification!