版本

no-restricted-globals

禁止使用指定的全域變數

如果您想透過啟用環境來允許一組全域變數,但仍然想禁止其中一些,那麼禁止使用特定的全域變數會很有用。

例如,早期的 Internet Explorer 版本將目前的 DOM 事件公開為全域變數 event,但是長期以來使用此變數被認為是不好的做法。限制此變數將確保此變數不會在瀏覽器程式碼中使用。

規則詳情

此規則允許您指定您不想在應用程式中使用的全域變數名稱。

選項

此規則接受字串列表,其中每個字串都是要限制的全域變數

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

或者,該規則也接受物件,其中指定了全域變數名稱和可選的自訂訊息

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

針對範例全域變數名稱 "event", "fdescribe"不正確程式碼範例

在遊樂場中開啟
/*global event, fdescribe*/
/*eslint no-restricted-globals: ["error", "event", "fdescribe"]*/

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

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

針對範例全域變數名稱 "event"正確程式碼範例

在遊樂場中開啟
/*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" 以及自訂錯誤訊息的不正確程式碼範例

在遊樂場中開啟
/*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 中引入。

資源

變更語言