如果您希望通过启用环境来允许一组全局变量,但仍希望禁止其中某些变量,则禁止使用特定的全局变量非常有用。
例如,早期的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: "error", message: "Use local parameter instead." }] */function onClick() {console.log(event); // Unexpected global variable 'event'. Use local parameter instead.}
const mycode = 1;// 错误的写法if(isNaN(mycode)){console.log(mycode);}// ESLint提示: "Unexpected use of 'isNaN'."// 正确的写法if(Number.isNaN(mycode)){console.log(mycode);}
"rules":{"no-restricted-globals":"off"}
eslint使用注意事项
eslint环境变量设置
该规则禁止词法声明(`let`,`const`,`function`和`class`在)`case/ default`条款。原因是词法声明在整个开关块中是可见的,但只有在分配时才会被初始化,这只有在达到定义它的情况下才会发生。
如果您希望通过启用环境来允许一组全局变量,但仍希望禁止其中某些变量,则禁止使用特定的全局变量非常有用。 例如,早期的Internet Explorer版本将当前的DOM事件暴露为全局变量 event,但是长期以来,使用此变量一直被认为是一种不好的做法。限制此操作将确保在浏览器代码中不使用此变量。