no-undef
除非在 /*global */
註解中提及,否則不允許使用未宣告的變數
✅ 推薦
在設定檔中使用 @eslint/js
的 recommended
設定會啟用此規則
此規則可以幫助您找到因變數和參數名稱拼寫錯誤或意外的隱式全域變數(例如,忘記在 for
迴圈初始化器中使用 var
關鍵字)而導致的潛在 ReferenceError。
規則詳情
除非變數在 /*global ...*/
註解中明確提及,或在設定檔中的 globals
鍵中指定,否則任何對未宣告變數的引用都會導致警告。這些的常見用途是如果您有意使用在其他地方定義的全域變數(例如,在從 HTML 來源的腳本中)。
此規則的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-undef: "error"*/
var foo = ();
var bar = + 1;
此規則的正確程式碼範例,使用 global
宣告
在遊樂場中開啟
/*global someFunction, a*/
/*eslint no-undef: "error"*/
var foo = someFunction();
var bar = a + 1;
請注意,此規則不禁止對唯讀全域變數進行賦值。如果您也想禁止這些賦值,請參閱no-global-assign。
此規則也不禁止重新宣告全域變數。如果您也想禁止這些重新宣告,請參閱no-redeclare。
選項
typeof
設定為 true 時,會針對 typeof 檢查中使用的變數發出警告(預設為 false)。
typeof
預設 { "typeof": false }
選項的正確程式碼範例
在遊樂場中開啟
/*eslint no-undef: "error"*/
if (typeof UndefinedIdentifier === "undefined") {
// do something ...
}
如果您想防止對尚未宣告的變數進行 typeof
檢查,則可以使用此選項。
{ "typeof": true }
選項的錯誤程式碼範例
在遊樂場中開啟
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof === "string"){}
{ "typeof": true }
選項使用 global
宣告的正確程式碼範例
在遊樂場中開啟
/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */
if(typeof a === "string"){}
何時不使用它
如果不明確宣告全域變數不符合您的喜好。
相容性
此規則提供與 JSHint 和 JSLint 中處理全域變數的相容性。
由 TypeScript 處理
當使用 TypeScript 時,禁用此規則是安全的,因為 TypeScript 的編譯器會強制執行此檢查。
相關規則
版本
此規則是在 ESLint v0.0.9 中引入的。