no-undef
禁止使用未声明的变量,除非在 /*global */
注释中提及
在 配置文件 中使用来自 @eslint/js
的 recommended
配置可以启用此规则
此规则可以帮助你定位因变量和参数名称拼写错误或意外隐式全局变量(例如,忘记 for
循环初始化程序中的 var
关键字)导致的潜在 ReferenceErrors。
¥This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var
keyword in a for
loop initializer).
规则详情
¥Rule Details
对未声明变量的任何引用都会导致警告,除非该变量在 /*global ...*/
注释中明确提及,或在 配置文件中的 globals
键 中指定。这些的一个常见用例是,如果你有意使用在其他地方定义的全局变量(例如,在源自 HTML 的脚本中)。
¥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).
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-undef: "error"*/
var foo = someFunction();
var bar = a + 1;
使用 global
声明的此规则的正确代码示例:
¥Examples of correct code for this rule with global
declaration:
/*global someFunction, a*/
/*eslint no-undef: "error"*/
var foo = someFunction();
var bar = a + 1;
请注意,此规则不允许分配给只读全局变量。如果你还想禁止这些分配,请参阅 no-global-assign。
¥Note that this rule does not disallow assignments to read-only global variables. See no-global-assign if you also want to disallow those assignments.
该规则也不允许重新声明全局变量。如果你还想禁止这些重新声明,请参阅 no-redeclare。
¥This rule also does not disallow redeclarations of global variables. See no-redeclare if you also want to disallow those redeclarations.
选项
¥Options
-
typeof
设置为 true 将对 typeof 检查中使用的变量触发警告(默认为 false)。¥
typeof
set to true will warn for variables used inside typeof check (Default false).
typeof
默认 { "typeof": false }
选项的正确代码示例:
¥Examples of correct code for the default { "typeof": false }
option:
/*eslint no-undef: "error"*/
if (typeof UndefinedIdentifier === "undefined") {
// do something ...
}
如果你想防止 typeof
检查尚未声明的变量,你可以使用此选项。
¥You can use this option if you want to prevent typeof
check on a variable which has not been declared.
{ "typeof": true }
选项的错误代码示例:
¥Examples of incorrect code for the { "typeof": true }
option:
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
具有 global
声明的 { "typeof": true }
选项的正确代码示例:
¥Examples of correct code for the { "typeof": true }
option with global
declaration:
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
何时不使用
¥When Not To Use It
如果全局变量的显式声明不符合你的口味。
¥If explicit declaration of global variables is not to your taste.
兼容性
¥Compatibility
此规则提供与 JSHint 和 JSLint 中的全局变量处理的兼容性。
¥This rule provides compatibility with treatment of global variables in JSHint and JSLint.
由 TypeScript 处理
使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。
相关规则
版本
此规则是在 ESLint v0.0.9 中引入。