First, we have to install jquery, npm install jquery. The installed version is 3.1.0
Next, the first feeling we will use var $ = require('jquery') .
Save the following code as
var $ = require('jquery') $("body").append("<div>TEST</div>"); ($("body").html());
Run node . Tip error:
Error: jQuery requires a window with a document
So what should we do?
existnpm jquery installation package home page, we see that it can be usedjsdom Perform a simulation of a document.
require("jsdom").env("", function(err, window) { if (err) { (err); return; } var $ = require("jquery")(window); $("body").append("<div>TEST</div>"); ($("body").html()); });
Run, the result is OK.
One thing that makes me uncomfortable with the above code is that I have to operate in the callback function. So how can we not introduce jquery into the callback function?
var $ = require('jquery')(require("jsdom").jsdom().defaultView); $("body").append("<div>TEST</div>"); ($("body").html());
It runs OK.