首页
Javascript
Html
Css
Node.js
Electron
移动开发
小程序
工具类
服务端
浏览器相关
前端收藏
其他
关于
公司注册

eslint:no-restricted-globals

2018年12月28日 发布 阅读(4633) 作者:Jerman

禁止特定的全局变量

如果您希望通过启用环境来允许一组全局变量,但仍希望禁止其中某些变量,则禁止使用特定的全局变量非常有用。

例如,早期的Internet Explorer版本将当前的DOM事件暴露为全局变量 event,但是长期以来,使用此变量一直被认为是一种不好的做法。限制此操作将确保在浏览器代码中不使用此变量。

规则细节

此规则允许您指定不希望在应用程序中使用的全局变量名称。

选项

此规则采用字符串列表,其中每个字符串都是要限制的全局字符串:

  1. {
  2. "rules": {
  3. "no-restricted-globals": ["error", "event", "fdescribe"]
  4. }
  5. }

或者,规则还接受对象,其中指定了全局名称和可选的自定义消息:

  1. {
  2. "rules": {
  3. "no-restricted-globals": [
  4. "error",
  5. {
  6. "name": "event",
  7. "message": "Use local parameter instead."
  8. },
  9. {
  10. "name": "fdescribe",
  11. "message": "Do not commit fdescribe. Use describe instead."
  12. }
  13. ]
  14. }
  15. }

示例全局变量名称的错误代码示例”event”, “fdescribe”:

  1. /*global event, fdescribe*/
  2. /*eslint no-restricted-globals: ["error", "event", "fdescribe"]*/
  3. function onClick() {
  4. console.log(event);
  5. }
  6. fdescribe("foo", function() {
  7. });

示例全局变量名称的正确代码示例”event”:

  1. /*global event*/
  2. /*eslint no-restricted-globals: ["error", "event"]*/
  3. import event from "event-module";
  4. /*global event*/
  5. /*eslint no-restricted-globals: ["error", "event"]*/
  6. var event = 1;

示例全局变量名称的错误代码示例”event”以及自定义错误消息:

  1. /*global event*/
  2. /* eslint no-restricted-globals: ["error", { name: "error", message: "Use local parameter instead." }] */
  3. function onClick() {
  4. console.log(event); // Unexpected global variable 'event'. Use local parameter instead.
  5. }

应用例子

isNaN
  1. const mycode = 1;
  2. // 错误的写法
  3. if(isNaN(mycode)){
  4. console.log(mycode);
  5. }
  6. // ESLint提示: "Unexpected use of 'isNaN'."
  7. // 正确的写法
  8. if(Number.isNaN(mycode)){
  9. console.log(mycode);
  10. }

关闭此规则

  1. "rules":{
  2. "no-restricted-globals":"off"
  3. }
版权声明:本站文章除特别声明外,均采用署名-非商业性使用-禁止演绎 4.0 国际 许可协议,如需转载,请注明出处
  • ESLint的使用

    eslint使用注意事项

    发布:2019-01-03 阅读(3484)

  • 'define' is not defined.'$' is not defined.

    eslint环境变量设置

    发布:2019-01-02 阅读(5843)

  • eslint:no-case-declarations

    该规则禁止词法声明(`let`,`const`,`function`和`class`在)`case/ default`条款。原因是词法声明在整个开关块中是可见的,但只有在分配时才会被初始化,这只有在达到定义它的情况下才会发生。

    发布:2018-12-28 阅读(3096)

  • eslint:no-restricted-globals

    如果您希望通过启用环境来允许一组全局变量,但仍希望禁止其中某些变量,则禁止使用特定的全局变量非常有用。 例如,早期的Internet Explorer版本将当前的DOM事件暴露为全局变量 event,但是长期以来,使用此变量一直被认为是一种不好的做法。限制此操作将确保在浏览器代码中不使用此变量。

    发布:2018-12-28 阅读(4633)