ESLint 的“ no-undef”规则将我对 Underscore 的使用称为未定义变量

我使用 Grunt 作为我的构建工具,使用 ESLint 作为我正在开发的应用程序的清理工具。我还使用了 Underscore Node 包,并在我的应用程序中使用了它。不幸的是,当我在我的代码上运行 ESLint 时,它认为 _ 是下面一行中未定义的变量:

return _.pluck(objects, nameColumn);

这就是它给我带来的错误:

78:21 error "_" is not defined no-undef

我希望不要为 ESLint 禁用 no-undef 规则,并且我已经尝试安装 Underscore 插件,但是我仍然收到这个错误。如果其他任何人有任何想法尝试这一点,我将非常感激!

如果有任何进一步的信息,我可以提供,可以帮助任何人帮助我得到这个解决,只要让我知道!

78973 次浏览

The official documentation should give you an idea on how to fix this.

Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a /*global ...*/ comment, or specified in the globals key in the configuration file.

The easiest fix would be to add

/* global _ */

at the top of your file.

Or better, explicitly specify that the variable is read-only, to disallow overwriting the variable:

/* global _:readonly */

But since you'll have to do that for each new js file, it can get annoying. If you are using underscore often, I'd suggest to add globals to your .eslintrc file, for example:

{
"globals": {
"_": "readonly"
}
}

And save this as .eslintrc in your project root, or optionally in your user home directory. Although some say the latter not recommended, it can sometimes be convenient, but you have to remember that you have it there :)


Explanation of the above rule: "_": "readonly" (used to be "_": false, now deprecated) means that a variable named _ tells eslint that this variable is defined globally and it will not emit any no-undef errors for this variable. As @sebastian pointed out, "readonly" (or false - deprecated) means that the variable can't be overwritten, so the code _ = 'something else' would yield an error no-global-assign. If you were to instead use "_": "writable" (or "_": true - deprecated), this means that the value can be re-assigned and the previously mentioned error will not occur.

But keep in mind that this will only happen if you assign directly to the global variable as I have shown in the example. You can still shadow it and eslint won't say anything. For example, these snippets wouldn't yield the no-global-assign:

const _ = 'haha I broke your _'

or as function argument name, e.g.

function (_) {
console.log(_, 'might not be the _ you were looking for')
}

If you are using jest for testing - in your environment - in eslintrc.json

"env":{
"jest":true
}