为 no-undef 设置忽略列表(从其他来源定义预期变量)

Set ignore list for no-undef (Defining expected variables from other sources)

我有一些 js 代码,在测试过程中会分多个部分加载,并为产品进行连接和丑化。

我有一个配置文件,它定义了一个变量 myConfig 和业务逻辑脚本,它期望 myConfig 被设置并全局可用。

这工作正常,在开发或生产期间没有错误。

问题是我想使用 no-undef eslint 规则从丢失的声明中捕获其他变量和函数。所以我正在寻找定义一组预期变量的方法。

有没有办法定义这样的变量?

来自rule documentation

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. A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML).

此外,

Specifying Globals

The no-undef rule will warn on variables that are accessed but not defined within the same file. If you are using global variables inside of a file then it’s worthwhile to define those globals so that ESLint will not warn about their usage. You can define global variables either using comments inside of a file or in the configuration file.

To specify globals using a comment inside of your JavaScript file, use the following format:

/* global var1, var2 */

This defines two global variables, var1 and var2. If you want to optionally specify that these global variables should never be written to (only read), then you can set each with a false flag:

/* global var1:false, var2:false */

To configure global variables inside of a configuration file, use the globals key and indicate the global variables you want to use. Set each global variable name equal to true to allow the variable to be overwritten or false to disallow overwriting. For example:

{
    "globals": {
        "var1": true,
        "var2": false
   }
}

And in YAML:

---
  globals:
    var1: true
    var2: false

These examples allow var1 to be overwritten in your code, but disallow it for var2.