Node.js & JQuery: “ReferenceError: $ is not defined” error. How do I use jquery with node on the server?

后端 未结 4 1560
太阳男子
太阳男子 2021-01-21 02:21

Help! I\'m trying to use jquery in my node.js app, but I keep getting an error when I try to use \'$\', saying \"$ is not defined\"... but I defined it at the top! Here\'s what

4条回答
  •  走了就别回头了
    2021-01-21 02:47

    Your doSomething function is declared outside if the bounds of the jsdom.env function. $ is only accessible inside that callback. Something like this should work:

    var $;
    
    require("jsdom").env("", function(err, window) {
        if (err) {
            console.error(err);
            return;
        }
        $ = require("jquery")(window);
        doSomething();
    });
    
     function doSomething(){
        var deferred = $.Deferred();
    }
    

    Though I think it would be more idiomatic to just declare doSomething inside the callback. That way it would have access to jquery from the outer scope.

    require("jsdom").env("", function(err, window) {
        if (err) {
            console.error(err);
            return;
        }
    
        function doSomething(){
            var deferred = $.Deferred();
         }
        var $ = require("jquery")(window);
        doSomething();
    });
    

提交回复
热议问题