davidx1
davidx1

Reputation: 3673

How to catch undeclared variable in React with ESLint?

I noticed the other day that ESLint lets me use undefined variables. Here's a simple example:

import React from 'react';

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

Visual Studio Code with ESLint plugin does not draw a red line under that first 'b'. When compiled with webpack, there are no eslint errors. When running in the browser, the console doesn't even log any errors. The only way I know something is wrong is nothing is being displayed on the screen.

Weirdly enough, if i remove the 'var b = 1', ESLint will give me an error saying b is undefined.

Here is my eslint config; nothing special

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

}

What is the problem here? And how can I configure ESLint to catch errors like this in the future?

Thanks

Upvotes: 4

Views: 3027

Answers (1)

cartant
cartant

Reputation: 58420

The rule you are looking for is no-use-before-define:

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

You are using the recommended configuration - in which that rule is not enabled. To use it, you will need to enable it explicitly:

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

Upvotes: 5

Related Questions