no-restricted-globals

禁止指定的全局变量

如果你想通过启用环境来允许一组全局变量,但仍想禁止其中一些变量,则禁止使用特定的全局变量会很有用。

¥Disallowing usage of specific global variables can be useful if you want to allow a set of global variables by enabling an environment, but still want to disallow some of those.

例如,早期的 Internet Explorer 版本将当前 DOM 事件暴露为全局变量 event,但长期以来,使用此变量一直被认为是一种不好的做法。限制这一点将确保此变量不在浏览器代码中使用。

¥For instance, early Internet Explorer versions exposed the current DOM event as a global variable event, but using this variable has been considered as a bad practice for a long time. Restricting this will make sure this variable isn’t used in browser code.

规则详情

¥Rule Details

此规则允许你指定不想在应用中使用的全局变量名称。

¥This rule allows you to specify global variable names that you don’t want to use in your application.

选项

¥Options

此规则采用字符串列表,其中每个字符串都是要限制的全局字符串:

¥This rule takes a list of strings, where each string is a global to be restricted:

{
    "rules": {
        "no-restricted-globals": ["error", "event", "fdescribe"]
    }
}

或者,该规则还接受对象,其中指定了全局名称和可选的自定义消息:

¥Alternatively, the rule also accepts objects, where the global name and an optional custom message are specified:

{
    "rules": {
        "no-restricted-globals": [
            "error",
            {
                "name": "event",
                "message": "Use local parameter instead."
            },
            {
                "name": "fdescribe",
                "message": "Do not commit fdescribe. Use describe instead."
            }
        ]
    }
}

示例 "event", "fdescribe" 全局变量名称的错误代码示例:

¥Examples of incorrect code for sample "event", "fdescribe" global variable names:

在线运行
/*global event, fdescribe*/
/*eslint no-restricted-globals: ["error", "event", "fdescribe"]*/

function onClick() {
    console.log(event);
}

fdescribe("foo", function() {
});

示例 "event" 全局变量名称的正确代码示例:

¥Examples of correct code for a sample "event" global variable name:

在线运行
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/

import event from "event-module";
在线运行
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/

var event = 1;

示例 "event" 全局变量名称的错误代码示例以及自定义错误消息:

¥Examples of incorrect code for a sample "event" global variable name, along with a custom error message:

在线运行
/*global event*/
/* eslint no-restricted-globals: ["error", { name: "event", message: "Use local parameter instead." }] */

function onClick() {
    console.log(event);    // Unexpected global variable 'event'. Use local parameter instead.
}

版本

此规则是在 ESLint v2.3.0 中引入。

资源

ESLint 中文网
粤ICP备13048890号