简体   繁体   English

节点无法加载应用程序,因为它无法识别jQuery

[英]node can't load app because it doesn't recognise jQuery

I'm trying to use Node to debug a Javascript file that contains some JQuery. 我正在尝试使用Node调试包含一些JQuery的Javascript文件。 but when loading files it gets not recognized on $. 但是在加载文件时,它在$上无法识别。 I've installed JQuery to local package ( npm install jquery -save-dev ). 我已经将JQuery安装到本地软件包( npm install jquery -save-dev )。

" npm jquery -version " result is 6.9.8 npm jquery -version ”结果是6.9.8

Code : 代码

$("#modalAddRole").on("modal:visible", function () {
    $("#roleName").val("");
    $("#roleName").focus();
});

jQuery manipulates the dom. jQuery操作dom。

node.js does not have a dom. node.js没有dom。

You'll need to create a virtual dom (that does not display) 您需要创建一个虚拟dom(不显示)

for that use jsdom to load your webpage/app and then execute whatever dom manipulation code you want. 为此,请使用jsdom加载您的网页/应用,然后执行所需的任何dom操作代码。

Example: 例:

const jsdom = require("jsdom");
const {JSDOM} = jsdom;
const jquery = require('jquery');

JSDOM.fromURL("https://url_To_Your_WebPage_Local_Or_Remote.com")
  .then(dom => {
    const $ = jquery(dom.window);
    //your jQuery code here
  })

I've installed JQuery to local package 我已经将JQuery安装到本地软件包

Installing it isn't enough. 仅安装还不够。 You need to load it into your program… 您需要将其加载到程序中…

const $ = require('jquery');

… and then $("#modalAddRole") isn't going to do anything until you load your HTML into it. …然后$("#modalAddRole")在将HTML加载到其中之前不会做任何事情。

See the documentation : 请参阅文档

For jQuery to work in Node, a window with a document is required. 为了使jQuery在Node中工作,需要一个带有文档的窗口。 Since no such window exists natively in Node, one can be mocked by tools such as jsdom. 由于Node本身不存在这样的窗口,因此可以通过jsdom之类的工具来模拟。 This can be useful for testing purposes. 这对于测试目的很有用。

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

But this seems like a very complicated approach to getting a debugging environment running. 但这似乎是使调试环境运行的非常复杂的方法。 Assuming the production environment for the code in the browser, it would make a lot more sense to debug it in the browser . 假设在浏览器的代码,生产环境,它将使很多更有意义调试它在浏览器中

Browsers have excellent debugging tools built-in these days, and simulating all the things browsers do by default is likely to make debugging harder because the debug environment is signficantly different to the production environment. 浏览器如今内置了出色的调试工具,由于调试环境与生产环境明显不同,因此模拟浏览器默认执行的所有操作可能会使调试更加困难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM