简体   繁体   中英

Jquery error '$ is not a function' in Node.js

I am getting the console error '$ is not a function' when using Jquery with Jsdom. I am using the latest Jquery version 3.3.1 and Jsdom 13.2.0. I am also using Browserify in order to utilize require.

main.js

var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { window } = new JSDOM();
const { document } = (new JSDOM('')).window;
global.document = document;

var $ = jQuery = require('jquery')(window);

$("body").click(function() {
  $("#name-tag").fadeOut("slow", function() {
    // Animation complete.
  });
});

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale = 1.0, maximum-scale=1.0, user-scalable=no"
    />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="scss/styles.css" />
    <script src="js/bundle.js"></script>
  </head>
  <body>
    <div id="name-tag">
    <h1>Hello World</h1>
    </div>
  </body>
</html>

Get rid of (window) after require('jquery') , so it should just be:

var $ = jQuery = require('jquery');

What you've written is redefining $ and jQuery as if you'd done:

jQuery = require('jquery');
var $ = jQuery = jQuery(window);

BTW, you can't declare two variables by chaining assignments like that. Only the first variable is being declared locally, the second one is an assignment without a declaration. If you want to declare two variables and given them the same value, do it in two steps:

var $, jQuery;
$ = jQuery = require('jquery');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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