How to use npm jquery module?

93,727

Solution 1

To use jquery in node, you need to have two separate node package installations.

  1. jquery
  2. jsdom to create a dummy window object which jquery can use.

Installation:

npm install jquery
npm install jsdom

In code:

var jsdom = require("jsdom").jsdom;
global.$ = require('jquery/dist/jquery')(jsdom().createWindow());

Or, with newer versions of jsdom:

require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

Using global.$ will make the jquery object($) available globally in your project.

Solution 2

You can use as below to handle as usual:

var $;
$ = require('jquery');
$('.tag').click(function() {
  return console.log('clicked');
});
Share:
93,727

Related videos on Youtube

Pio
Author by

Pio

"A day without sunshine is like, you know, night." SOreadytohelp

Updated on June 14, 2020

Comments

  • Pio
    Pio about 4 years

    How should I requirethe jquery in node if I use it in multiple modules? Should I define it as a global or should I just use the require('jquery)` in every module I need it?

    I am getting an error when trying to use the package.

    TypeError: Object function ( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            } has no method 'isArray'
    

    It looks like a bug in the current release as it should not check if I am running it in a browser according to the official documentation. This issue is also mentioned in another post. It works with version 1.8.3 as mentioned in one of the answers.

  • rodrigocfd
    rodrigocfd over 5 years
    This works well for Node.js. And if you're on TypeScript, don't forget to npm i --save-dev @types/jquery.
  • Dan Ortega
    Dan Ortega about 4 years
    Thanks Rodrigo, this helped a lot.