Error: jQuery requires a window with a document

后端 未结 12 2327
说谎
说谎 2020-11-29 00:43

So everything was working just fine and great until doing npm update and now things do not work quite as they used to.

A little background: in my code I use jquery

12条回答
  •  执笔经年
    2020-11-29 01:33

    The npm package for jQuery definitely used to include jsdom with it, which is why it would work at all in Node: jQuery needs to have some kind of DOM environment to work with.

    You can check that old versions used to have it by doing npm install jquery@1.8.3. You'll see jsdom being installed with it. For some reason they seem to have removed jsdom from the recent releases. I don't know why.

    However, using jsdom 7.x to run jQuery code is simple:

    var jsdom = require("jsdom");
    var window = jsdom.jsdom().defaultView;
    
    jsdom.jQueryify(window, "http://code.jquery.com/jquery.js", function () {
      var $ = window.$;
      $("body").prepend("

    The title

    "); console.log($("h1").html()); });

    The path could be changed to a different version of jQuery or to a local file.

    Note: Earlier versions of jsdom, including the 3.x series, would need the line var window = jsdom.jsdom().parentWindow; instead of var window = jsdom.jsdom().defaultView;. 4.x made it so that parentWindow no longer works.

提交回复
热议问题