从Node初始化jquery

Loic Tregan

我正在使用以下内容创建一个新项目:

$mkdir X
$cd X
$npm install jquery

然后创建一个新的app.js文件:

var http = require('http');
var $ = require('jquery');
console.log("http="+ http);
console.log("$="+ $);
console.log("$.getJSON="+ $.getJSON);

输出为:

http=[object Object]
$=function ( w ) {...}
$.getJSON=undefined

为什么$ .getJSON是undefined?使用最新的io.js v2.4.0。

颜照片

您正在尝试XHR从Node.js中创建一个由于Node.js只是JavaScript运行时,并且与浏览器不同,因此无法正常工作。

如果您想通过HTTP协议从某处获取内容,可以使用request例如(来自官方文档):

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage. 
  }
})

您可以查看此答案(也是我的答案),以获取有关将jQuery与Node.js结合使用的更多信息。

UPDATE [再次输入!]:

因此,您想知道jQuery节点模块如何区分浏览器和节点环境吗?当您require在提供module的CommonJS或类似环境中使用jQuery时module.exports,得到的是工厂而不是实际的jQuery对象。如下所示,该工厂可用于创建jQuery对象,即使用jsdom

let jsdom = require("jsdom");
let $ = null;

jsdom.env(
  "http://quaintous.com/2015/07/31/jquery-node-mystery/",
  function (err, window) {
    $ = require('jQuery')(window);
  }
);

这是jQuery区分浏览器和io.js(或Node.js)的方式:

(function( global, factory ) {

    if ( typeof module === "object" && typeof module.exports === "object" ) {
        // For CommonJS and CommonJS-like environments where a proper `window`
        // is present, execute the factory and get jQuery.
        // For environments that do not have a `window` with a `document`
        // (such as Node.js), expose a factory as module.exports.
        // This accentuates the need for the creation of a real `window`.
        // e.g. var jQuery = require("jquery")(window);
        // See ticket #14549 for more info.
        module.exports = global.document ?
            factory( global, true ) :
            function( w ) {
                if ( !w.document ) {
                    throw new Error( "jQuery requires a window with a document" );
                }
                return factory( w );
            };
    } else {
        factory( global );
    }

// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
  // implementation

  return jQuery;
}));

我将使用jQuery的npm包用于自定义构建,而不是与require一起使用

更新

我觉得这个主题恰好使一些开发人员忙,所以我结合了自己的答案,并写了一篇有关整个jQuery / Node组合的文章!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章