简体   繁体   中英

jshint error: Redefinition of '$'

I have a Node.js web application where I use Backbone.js and jQuery. My main js file is app.js where I include all the necessary scripts, including jQuery. So, this is the beginning of my app.js code:

'use strict';

var _ = require('lodash');
var $ = require('jquery');
var B = require('backbone');
B.$ = $;

Now if I run grunt on my project, it raises errors at the line where jQuery is loaded to $. It shows me this:

Linting public/js/app.js ...ERROR
[L4:C5] W079: Redefinition of '$'.
var $ = require('jquery');

I can still get everything running with grunt --force , but I would like to eliminate this error anyway. Can somebody explain why it raises the error and how to fix it?


My .jshintrc file:

{
    "laxcomma": true
    ,"laxbreak": true
    ,"curly": true
    ,"eqeqeq": true
    ,"immed": true
    ,"latedef": true
    ,"newcap": true
    ,"noarg": true
    ,"sub": true
    ,"undef": true
    ,"unused": false
    ,"asi": true
    ,"boss": true
    ,"eqnull": true
    ,"node": true
    ,"browser": true
    ,"jquery": true
    ,"predef":
    [
        "suite"
        ,"test"
        ,"setup"
        ,"teardown"
        ,"suiteSetup"
        ,"suiteTeardown"
        ,"requestAnimationFrame"
    ]
}

In jshint docs: http://www.jshint.com/docs/options/

jquery = true 
This option defines globals exposed by the jQuery JavaScript library.

You are telling jshint that jquery exists, thus he assumes that $ is defined. Remove the "jquery" : true" and your issue should go away.

Add this at the top of the file to make that error go away:

/* jshint -W079 */

What's happening here is that JQuery defines the $ variable, so JSHint views this as a piece of "potentially dangerous code"

A better solution would be to require jquery directly which should give you access to the $ variable globally.

Random guess: do you include jquery somewhere else? For example in some html file as a script. Or some other script might be defining global jquery variable.

Make sure that in your .jshintrc you don't have '$' set as predefined.

// Predefined Globals
"predef" : ["$"]   

If it is, remove.

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