版本

no-undef

禁止使用未声明的变量,除非在 /*global */ 注释中提及

推荐

配置文件 中使用来自 @eslint/jsrecommended 配置会启用此规则

此规则可以帮助您找到潜在的 ReferenceError,这些错误可能是由于变量和参数名称拼写错误,或意外的隐式全局变量(例如,忘记了 for 循环初始化器中的 var 关键字)。

规则详情

任何对未声明变量的引用都会导致警告,除非该变量在 /*global ...*/ 注释中显式提及,或在配置文件中的 globals中指定。 这些的常见用例是如果您有意使用在其他地方定义的全局变量(例如,在从 HTML 来源的脚本中)。

此规则的 错误 代码示例

在 Playground 中打开
/*eslint no-undef: "error"*/

const foo = someFunction();
const bar = a + 1;

此规则的 正确 代码示例,带有 global 声明

在 Playground 中打开
/*global someFunction, a*/
/*eslint no-undef: "error"*/

const foo = someFunction();
const bar = a + 1;

请注意,此规则不允许赋值给只读全局变量。 如果您也想禁止这些赋值,请参阅 no-global-assign

此规则也不禁止重新声明全局变量。 如果您也想禁止这些重新声明,请参阅 no-redeclare

选项

  • typeof 设置为 true 将警告在 typeof 检查中使用的变量(默认为 false)。

typeof

默认 { "typeof": false } 选项的 正确 代码示例

在 Playground 中打开
/*eslint no-undef: "error"*/

if (typeof UndefinedIdentifier === "undefined") {
    // do something ...
}

如果您想阻止对未声明的变量进行 typeof 检查,您可以使用此选项。

{ "typeof": true } 选项的 错误 代码示例

在 Playground 中打开
/*eslint no-undef: ["error", { "typeof": true }] */

if(typeof a === "string"){}

{ "typeof": true } 选项的 正确 代码示例,带有 global 声明

在 Playground 中打开
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */

if(typeof a === "string"){}

何时不使用它

如果显式声明全局变量不符合您的口味。

兼容性

此规则提供与 JSHintJSLint 中全局变量处理的兼容性。

由 TypeScript 处理

当使用 TypeScript 时,禁用此规则是安全的,因为 TypeScript 的编译器会强制执行此检查。

版本

此规则在 ESLint v0.0.9 中引入。

资源

更改语言