在node中服务器端使用jquery遇到jQuery requires a window with a document
使用jquery版本为v3.1.1,nodejs版本为4.0.3
原因在于jquery的运行需要window的运行环境,在浏览器端是没问题的,而在服务器上就不包含了,需要jsdom创建一个window给它.
jquery
文档解释如下:
// For CommonJS and CommonJS-like environments where a proper
window
// is present, execute the factory and get jQuery.
// For environments that do not have awindow
with adocument
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a realwindow
.
// e.g. var jQuery = require(“jquery”)(window);
// See ticket #14549 for more info.
解决方法就是用jsdom
创建一个类似浏览器的窗口对象。
首先安装jsdom
npm install jsdom
然后使用它:
var jsdom = require(“jsdom”);
var $ = require(“jquery”)(jsdom.jsdom().defaultView);//下面就可以使用$了。
需注意的是,由于jsdom
版本更新问题,(我用的是9.8.3版本)jsdom().defaultView
这个写法在一些旧版本可能无效,比如之前用的是jsdom().createWindow()
。stackoverflow有过讨论,详见jsdom.jsdom missing a “createWindow” method
当然,最好的办法是看jsdom文档