Node.jsでJQuery.Deferredを動かしたかったら
これははまった。以下の記述で気づけた。
This is because reqyure(‘jquery’) requires a window object
引用元:Testing javascript code that uses require('jquery') in node - Stack Overflow
jquery.js内にも記述がある
// 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.
jQuery is mainly a DOM library. What would you use it for without a DOM?
そうは言うけど、ママ持ってきてさっと試したい時とかあるかもよ〜
確認1
const $ = require("jquery"); console.log($.toString());
function ( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }
確認2
const $ = require("jquery"); const window = ""; try { $(window); } catch (e) { console.log(e); }
Error: jQuery requires a window with a document
対応
GitHub - tmpvar/jsdom: A JavaScript implementation of the WHATWG DOM and HTML standards, for use with node.jsを使って、windowを用意する。
ES6ならDestructuring assignment - JavaScript | MDNを使って
const {JSDOM} = require("jsdom"); const {window} = new JSDOM(""); const $ = require("jquery")(window);
それ以前なら
const JSDOM = require("jsdom").JSDOM; const window = new JSDOM("").window; const $ = require("jquery")(window);
追記
しっかり書いてあった。。https://www.npmjs.com/package/jQuery
でも動かなかった。