如何使用npm jquery模块?
如果我在多个模块中使用它,我应该如何在node
require
jquery
? 我应该将其定义为全局还是应该在每个我需要的模块中使用require('jquery
)`?
尝试使用该软件包时出现错误。
TypeError: Object function ( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); } has no method 'isArray'
它看起来像当前版本中的错误,因为根据官方文档,它不应该检查我是否在浏览器中运行它。 这个问题也在另一篇文章中提到。 它与其中一个答案中提到的1.8.3
版本一起工作。
要在节点中使用jquery,需要安装两个独立的节点包。
- jQuery的
- jsdom来创build一个jquery可以使用的虚拟窗口对象。
安装:
npm install jquery npm install jsdom
在代码中:
var jsdom = require("jsdom").jsdom; global.$ = require('jquery/dist/jquery')(jsdom().createWindow());
或者,更新版本的jsdom:
var jsdom = require("jsdom").jsdom; jsdom.env("", function(err, window) { if (err) { console.error(err); return; } global.$ = require("jquery")(window); })
使用全局。$将使jquery对象($)在您的项目全局可用。
你可以像以下一样使用:
var $; $ = require('jquery'); $('.tag').click(function() { return console.log('clicked'); });
如果你正在使用jQuery的客户端的目的,这是我做到了这一点,我在使用玉模板引擎的平均堆栈。
例如; 比方说,我有这样简单的layout.jade
我将通过index.jade在单个页面应用程序上使用所有的jqueryfunction,我将像这样加载。
“`
extends layout block content script(type='text/javascript', src="http://code.jquery.com/jquery-1.9.1.min.js") div#container(style="min-width: 500px; height: 500px; margin: 0 auto") script. if (jQuery) { console.log("jQuery library is loaded!"); } else { console.log("jQuery library is not found!"); } $(function () { }); h1= title p Welcome to #{title}
“`