如何使用 ESLint 在 React 中捕获未声明的变量?

How to catch undeclared variable in React with ESLint?

前几天我注意到 ESLint 允许我使用未定义的变量。这是一个简单的例子:

import React from 'react';

export default class test extends React.Component {
    render(){
        var a = b;
        var b = 1;
        return <h1>{a}</h1>
    }
}

Visual Studio 使用 ESLint 插件的代码不会在第一个 'b' 下绘制红线。 使用 webpack 编译时,不会出现 eslint 错误。 在浏览器中 运行 时,控制台甚至不会记录任何错误。 我知道出现问题的唯一方法是屏幕上没有显示任何内容。

奇怪的是,如果我删除 'var b = 1',ESLint 会给我一个错误,说 b 未定义。

这是我的 eslint 配置;没什么特别的

{
"parser":"babel-eslint",
"plugins":[
    "react"
],
"rules":{ },
"extends":["eslint:recommended", "plugin:react/recommended"]

}

这里有什么问题?以及如何配置 ESLint 以在将来捕获此类错误?

谢谢

您要找的规则是no-use-before-define:

This rule will warn when it encounters a reference to an identifier that has not yet been declared.

您正在使用推荐的配置 - 其中未启用该规则。要使用它,您需要明确启用它:

{
  "parser":"babel-eslint",
  "plugins":[
    "react"
  ],
  "rules":{
    "no-use-before-define": "error"
  },
  "extends":["eslint:recommended", "plugin:react/recommended"]
}