Monday, 26 June 2017

Including jQuery in node.js

I just started working on Node.js and the first issue I encountered was integrating jQuery into the application. I tried the npm listed option but that didn't work. After googling, I found the below code that helped me include and use jQuery in node.


const jsdom = require('jsdom');
const {
    JSDOM
} = jsdom;
const {
    window
} = new JSDOM('<!DOCTYPE html>');
const $ = require('jQuery')(window);

After analyzing the code, I realized that a window with a document is required for jQuery to work in Node and node doesn't provide any such default window. So we use jsdom to mock it.