[英]How to resolve “jQuery requires a window with a document” with import
I'm getting jQuery requires a window with a document
error and it seems that I need an answer like: Error: jQuery requires a window with a document 我得到
jQuery requires a window with a document
错误jQuery requires a window with a document
并且似乎我需要一个类似的答案: 错误:jQuery需要带有文档的窗口
What I'm looking for is the correct syntax for this using import
rather than require
because I'm not require
-ing anything else in my Node app. 我正在寻找的是使用
import
而不是require
的正确语法,因为我require
在Node应用程序中添加其他任何内容。 I'm trying to get this to work in a React component. 我正在尝试让它在React组件中工作。 I tried:
我试过了:
import jsdom from 'jsdom';
import $ from 'jquery';
jsdom.jsdom().createWindow();
and: 和:
import jsdom from 'jsdom';
const $ = require('jquery')(jsdom.jsdom().createWindow());
But that's not getting me there. 但这并不能使我到达那里。 How do I resolve this?
我该如何解决?
NOTE : This only works for older versions of jsdom. 注意 :这仅适用于旧版本的jsdom。
I do this for the tests for using jQuery Mockjax in a Node context . 我这样做是为了在Node上下文中使用jQuery Mockjax进行测试 。 Essentially, I use the jsdom
env()
method to generate the window object with a blank HTML document: 本质上,我使用jsdom
env()
方法生成带有空白HTML文档的window对象:
const jsdom = require('jsdom');
let $;
jsdom.env('<html></html>', function (error, window) {
if (error) {
// handle this somehow
} else {
$ = require('jquery')(window);
// now you have it...
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.