简体   繁体   中英

How to get the jQuery methods on Node.js?

Using Object.keys($.fn) (or Object.keys(jQuery.fn) ) on the client side works fine to get the jQuery functions as array.

How can I use the jquery package from npm to get the same array?

I tried:

  • require("jquery").fn => undefined (since we have to initialize it providing the window object)
  • I tried to initialize the jQuery function like this:

     var $ = require("jquery")({ // Simulate the document object document: { createElement: function () { return { parentNode: { removeChild: function () { } } } } } }); 

    Running it this way I get this error:

     /home/...node_modules/jquery/dist/jquery.js:897 var div = document.createElement("div"); ^ TypeError: Cannot read property 'createElement' of undefined 

So, basically, I don't really want to use jQuery in Node.js but just to get the array of jQuery methods (like on the client), avoiding to hardcode it in the code.

Is this possible?

Try using https://github.com/tmpvar/jsdom , it provides a partial implementation of the DOM, especially for use in node, and even allows you to load jquery dynamically inside the mock window. Something like this:

var jsdom = require("jsdom");

jsdom.env(
  '<p></p>',
  ["http://code.jquery.com/jquery.js"],
  function (err, window) {
    console.log(Object.keys(window.$.fn));
  }
);

There are static methods and Instance methods in Jquery, do probably you want to have both, and clone them with Object.assign().

You should try to iterate over both of them like :

var jsdom=require('jsdom').jsdom;
var document = jsdom("hello world");
var window = document.defaultView;

var jQuery=require('jquery')(window);


var clonedInstanceMethods = {};
for (var instancemethod in jQuery.prototype){
    Object.assign(clonedInstanceMethods,jQuery.prototype[instancemethod])
}

console.log(clonedInstanceMethods);

now do the same with the static methods ... something like that. you get the picture.

We use jsdom to create a window. should work now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM