no-undef
禁止使用未声明的变量,除非在 /*global */ 注释中提及
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
此规则可以帮助你定位由于变量和参数名称拼写错误,或意外的隐式全局变量(例如,在 for 循环初始化器中忘记使用 var 关键字)而产生的潜在 ReferenceError。
🌐 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"*/
const foo = someFunction();
const bar = a + 1;
使用 global 声明的此规则的正确代码示例:
🌐 Examples of correct code for this rule with global declaration:
/*global someFunction, a*/
/*eslint no-undef: "error"*/
const foo = someFunction();
const 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
默认 { "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 中引入。