jshint错误:重新定义'$'

时间:2014-07-01 12:51:10

标签: javascript jquery node.js backbone.js jshint

我有一个Node.js Web应用程序,我使用Backbone.js和jQuery。我的主要js文件是app.js,其中包含所有必需的脚本,包括jQuery。所以,这是我的app.js代码的开头:

'use strict';

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

现在如果我在我的项目上运行grunt,它会在jQuery加载到$的行引发错误。它告诉我这个:

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

我仍然可以使用grunt --force运行所有内容,但无论如何我想消除此错误。有人可以解释为什么它会引发错误以及如何解决它?


我的.jshintrc文件:

{
    "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"
    ]
}

4 个答案:

答案 0 :(得分:17)

在jshint docs中:http://www.jshint.com/docs/options/

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

你告诉jshint jquery存在,因此他认为$是定义的。移除"jquery" : true",您的问题就会消失。

答案 1 :(得分:6)

在文件顶部添加此项以使该错误消失:

/* jshint -W079 */

这里发生的是JQuery定义$变量,因此JSHint将其视为"potentially dangerous code"的一部分

更好的解决方案是直接使用jquery,这样可以让您全局访问$ variable。

答案 2 :(得分:0)

随机猜测:你在其他地方包含jquery吗?例如在一些html文件中作为脚本。或者其他一些脚本可能正在定义全局jquery变量。

答案 3 :(得分:0)

请确保您的.jshintrc中没有' $'设置为预定义。

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

如果是,请删除。

相关问题