版本

no-undef

禁止使用未宣告的變數,除非在 /*global */ 註解中提及

建議

設定檔中使用來自 @eslint/jsrecommended 設定會啟用此規則

此規則可以幫助您找到潛在的 ReferenceError,這些錯誤可能是由於變數和參數名稱拼寫錯誤,或意外的隱式全域變數(例如,忘記 for 迴圈初始化器中的 var 關鍵字)。

規則詳細資訊

任何對未宣告變數的引用都會導致警告,除非該變數在 /*global ...*/ 註解中明確提及,或在設定檔中的 globals中指定。 這些常見的用例是如果您有意使用在其他地方定義的全域變數(例如,在從 HTML 來源的腳本中)。

此規則的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-undef: "error"*/

const foo = someFunction();
const bar = a + 1;

此規則的正確程式碼範例,使用 global 宣告

在 Playground 中開啟
/*global someFunction, a*/
/*eslint no-undef: "error"*/

const foo = someFunction();
const bar = a + 1;

請注意,此規則不禁止對唯讀全域變數進行賦值。如果您也想禁止這些賦值,請參閱no-global-assign

此規則也不禁止重新宣告全域變數。如果您也想禁止這些重新宣告,請參閱no-redeclare

選項

  • typeof 設定為 true 將會警告在 typeof 檢查內使用的變數(預設為 false)。

typeof

預設 { "typeof": false } 選項的正確程式碼範例

在 Playground 中開啟
/*eslint no-undef: "error"*/

if (typeof UndefinedIdentifier === "undefined") {
    // do something ...
}

如果您想要防止對尚未宣告的變數進行 typeof 檢查,您可以使用此選項。

{ "typeof": true } 選項的錯誤程式碼範例

在 Playground 中開啟
/*eslint no-undef: ["error", { "typeof": true }] */

if(typeof a === "string"){}

{ "typeof": true } 選項使用 global 宣告的正確程式碼範例

在 Playground 中開啟
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */

if(typeof a === "string"){}

何時不該使用

如果明確宣告全域變數不符合您的喜好。

相容性

此規則提供與 JSHintJSLint 中全域變數處理方式的相容性。

由 TypeScript 處理

當使用 TypeScript 時,停用此規則是安全的,因為 TypeScript 的編譯器會強制執行此檢查。

版本

此規則在 ESLint v0.0.9 中引入。

資源

變更語言