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` 全域變數名稱的**錯誤**程式碼範例
在 Playground 中開啟
/*global event, fdescribe*/
/*eslint no-restricted-globals: ["error", "event", "fdescribe"]*/
function onClick() {
console.log();
}
("foo", function() {
});
範例 `event` 全域變數名稱的**正確**程式碼範例
在 Playground 中開啟
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/
import event from "event-module";
在 Playground 中開啟
/*global event*/
/*eslint no-restricted-globals: ["error", "event"]*/
const event = 1;
範例 `event` 全域變數名稱的**錯誤**程式碼範例,以及自訂錯誤訊息
在 Playground 中開啟
/*global event*/
/* eslint no-restricted-globals: ["error", { name: "event", message: "Use local parameter instead." }] */
function onClick() {
console.log(); // Unexpected global variable 'event'. Use local parameter instead.
}
相關規則
版本
這個規則在 ESLint v2.3.0 中引入。