简体   繁体   English

如何使用npm jquery模块?

[英]How to use npm jquery module?

How should I require the jquery in node if I use it in multiple modules? 如果我在多个模块中使用它,我应该如何在node require jquery Should I define it as a global or should I just use the require('jquery )` in every module I need it? 我应该将它定义为全局还是应该在我需要的每个模块中使用require('jquery )`?

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'

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. 它适用于其中一个答案中提到的1.8.3版本。

To use jquery in node, you need to have two separate node package installations. 要在节点中使用jquery,您需要安装两个单独的节点包。

  1. jquery jQuery的
  2. jsdom to create a dummy window object which jquery can use. jsdom创建一个jquery可以使用的虚拟窗口对象。

Installation: 安装:

npm install jquery
npm install jsdom

In code: 在代码中:

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

Or, with newer versions of jsdom: 或者,使用较新版本的jsdom:

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

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

Using global.$ will make the jquery object($) available globally in your project. 使用global。$将使jquery对象($)在您的项目中全局可用。

You can use as below to handle as usual: 您可以像往常一样使用如下处理:

var $;
$ = require('jquery');
$('.tag').click(function() {
  return console.log('clicked');
});

If you are using jQuery for client purposes this is how I did it and I am on MEAN stack using jade templating engine. 如果你正在使用jQuery用于客户端目的,我就是这样做的,而且我使用的是jade模板引擎在MEAN堆栈上。

For example; 例如; Let's say I have simple layout.jade like this 假设我有像这样的简单layout.jade 在此输入图像描述

I will be using all jquery functionality on a single page app via index.jade and I will be loading like this. 我将通过index.jade在单页应用程序上使用所有jquery功能,我将像这样加载。

在此输入图像描述

``` ```

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}

``` ```

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

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