如何使用npm jquery模块? [英] How to use npm jquery module?

查看:68
本文介绍了如何使用npm jquery模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在多个模块中使用require中的jquery,应该如何require?我应该将其定义为全局变量,还是在每个需要的模块中都使用require('jquery)`?

How should I requirethe jquery in node if I use it in multiple modules? Should I define it as a global or should I just use the require('jquery)` in every module I need it?

尝试使用该软件包时出现错误.

I am getting an error when trying to use the package.

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一起使用.

It looks like a bug in the current release as it should not check if I am running it in a browser according to the official documentation. This issue is also mentioned in another post. It works with version 1.8.3 as mentioned in one of the answers.

推荐答案

要在节点中使用jquery,您需要安装两个单独的节点软件包.

To use jquery in node, you need to have two separate node package installations.

  1. jquery
  2. jsdom创建一个jquery可以使用的虚拟窗口对象.

安装:

npm install jquery
npm install jsdom

在代码中:

var jsdom = require("jsdom").jsdom;
global.$ = require('jquery/dist/jquery')(jsdom().createWindow());

或者,使用较新版本的jsdom:

Or, with newer versions of jsdom:

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

    var $ = require("jquery")(window);
});

使用global.$将使jquery对象($)在您的项目中全局可用.

Using global.$ will make the jquery object($) available globally in your project.

这篇关于如何使用npm jquery模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆