ESLint 报错:未定义变量 dollar($)。 (no-undef)

148
我在我的项目中添加了ESLint。一切都很好,除了涉及到符号$的时候。
$("#ID").hide();

我遇到了这个错误:[eslint] '$' is not defined. (no-undef) 我的.eslintrc.json文件(注意:它设置了additional rules,禁止使用jQuery函数,当存在等效的JavaScript函数时):
{
"env": {
    "browser": true,
    "commonjs": true,
    "es6": true
},
"extends": [
    "eslint:recommended"
],
"parserOptions": {
    "sourceType": "module"
},
"plugins": [
    "dollar-sign",
    "jquery"
],
"rules": {       
    "indent": [
        "error" ,
        "tab"
    ],
    "linebreak-style": [
        "error",
        "windows"
    ],
    "quotes": [
        "error",
        "double"
    ],
    "semi": [
        "error",
        "always"
    ],
    "jquery/no-ajax": 2,
    "jquery/no-animate": 2,
    "jquery/no-attr": 2,
    "jquery/no-bind": 2,
    "jquery/no-class": 2,
    "jquery/no-clone": 2,
    "jquery/no-closest": 2,
    "jquery/no-css": 2,
    "jquery/no-data": 2,
    "jquery/no-deferred": 2,
    "jquery/no-delegate": 2,
    "jquery/no-each": 2,
    "jquery/no-fade": 2,
    "jquery/no-filter": 2,
    "jquery/no-find": 2,
    "jquery/no-global-eval": 2,
    "jquery/no-has": 2,
    "jquery/no-hide": 2,
    "jquery/no-html": 2,
    "jquery/no-in-array": 2,
    "jquery/no-is": 2,
    "jquery/no-map": 2,
    "jquery/no-merge": 2,
    "jquery/no-param": 2,
    "jquery/no-parent": 2,
    "jquery/no-parents": 2,
    "jquery/no-parse-html": 2,
    "jquery/no-prop": 2,
    "jquery/no-proxy": 2,
    "jquery/no-serialize": 2,
    "jquery/no-show": 2,
    "jquery/no-sizzle": 2,
    "jquery/no-slide": 2,
    "jquery/no-text": 2,
    "jquery/no-toggle": 2,
    "jquery/no-trigger": 2,
    "jquery/no-trim": 2,
    "jquery/no-val": 2,
    "jquery/no-wrap": 2,
    "dollar-sign/dollar-sign": [
        2,
        "ignoreProperties"
    ]
}

你可以看到我添加了两个插件:eslint-plugin-dollar-sign和eslint-plugin-jquery。
为什么这个规则不起作用?
"dollar-sign/dollar-sign": [
    2,
    "ignoreProperties"
]
5个回答

279

你遗漏了

"env": {
  "browser": true,
  "commonjs": true,
  "es6": true,
  "jquery": true
},

$在没有启用jquery环境的情况下不被声明为全局。因此,您会收到一个no-undef错误,表示您正在使用未声明的变量。


56

1
非常感谢,这让我免去了更改配置文件的麻烦。 - Divyang
谢谢!这比 /* global $ */ 更清晰明确。 - Noah Sussman

34

你也可以将此行代码添加到你的JS文件顶部:

/* global $ */
为了避免"$"等全局变量的警告,或者其他类似 "varName" 的情况:
/* global varName */

完美地工作了,添加“u”以支持umbrellajs :) (我想用谷歌搜索使用“$”的问题,因为这可能更常见) - Justin

27

1
这对于其他库非常有用,比如我的情况下是THREEjs。我通过添加"globals": { "THREE": true },来解决了eslint的警告问题,谢谢! - danivicario
1
一整天都在寻找这个解决方案,寻找webpack全局变量,这正是我所需要的。谢谢! - lharby

1

"env": { .... "jquery": true },

非常有帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接