How is ESLint integrated into Create React App?
Asked Answered
W

4

159

When I run npx create-react-app some-name, a bare-bones React project is created for me. When I then peek into package.json, there seems to be some evidence of ESLint being present, as there is this:

"eslintConfig": {
  "extends": "react-app"
},

Usually, when I install ESLint as a dev dependency and configure it, VS Code picks it up. In this case, VS Code does not seem to recognize that there is any kind of linter present/configured. This is not super surprising, as ESLint is not a dependency of the React project I just generated -- at least not according to package.json.
When I try to run eslint . within the project's root directory, it says "command not found".

I tried to breathe life into this ESLint configuration by expanding it, so now I have this:

"eslintConfig": {
  "extends": ["react-app", "eslint:recommended", "google"],
  "rules": {
    "semi": ["error", "always"],
    "quotes": ["error", "double"]
   }
},

This changes nothing. I manipulated the source code in a way that I know violates the above configuration, yet, I have not been signaled any wrongdoing.

This leads me to a simple question: Do projects generated by create-react-app come with some kind of ESLint configuration, and, if so, how do I enable and extend it correctly?

As I am being referred to the number one Google hit that comes up when searching "create react app eslint" -- which I have read -- let me clarify what I mean:

ESLint is obviously integrated into Create React App in a different way than it would be if it had been manually added to the project like so. This is not only evident by the sheer number of people who post about their struggles of getting the two to work together.
This is also evident as …

  • … one cannot run the eslint command in the project root.
  • … ESLint does not seem to be a dependency within package.json.
  • … VS Code doesn't pick up that there is ESLint present.
  • … there is no .eslintrc.* file in the project root.

So: How do I go about ESLint in the context of Create React App? For starters: How do I run it? How do I expand it? And why does VS Code not pick it up -- even though it usually notices the presence of ESLint?

Wheelbase answered 7/1, 2020 at 17:8 Comment(1)
This seems like a vscode linter configuration issue. I would review/play with the package settings. I see warnings in Atom automatically (with my properly configured linter settings I already have set up). If you want to see what CRA does under the hood, you can run yarn eject. Also, eslint SOMETHING only works if you have eslint installed globally. Try yarn eslint src or npx eslint src. If you're interested in customizing your ESLint config with CRA, check out my blog post: medium.com/hackernoon/a-simple-linter-setup-finally-d908877fa09Anestassia
S
86

Yes, create-react-app comes with eslint config.

How do I enable and extend it correctly?

You can check how to extend it here.

{
  "eslintConfig": {
    "extends": ["react-app", "shared-config"],
    "rules": {
      "additional-rule": "warn"
    },
    "overrides": [
      {
        "files": ["**/*.ts?(x)"],
        "rules": {
          "additional-typescript-only-rule": "warn"
        }
      }
    ]
  }
}

How do I enable it?

You need to integrate it with your IDE.

How do I run it?

After integrating it, an eslint server will be running in the background and will enable linting for your IDE (sometimes restarting IDE required).


I checked all your claims after running npx create-react-app example:

...one cannot run the eslint command in the project root.

You can:

enter image description here

eslint is installed as part of the project dependency, just by running eslint globally (eslint [cmd]) you need to ensure it installed globally (not recommended).

...ESLint does not seem to be a dependency within package.json.

Why should it be? That's why you using a starter like CRA. It's an inner dependency, you don't need to worry about it, that's CRA's job.

...VS Code doesn't pick up that there is ESLint present.

It does, check the OUTPUT tab and look for ESLint to see the server's output.

enter image description here

...there is no .eslintrc.* file in the project root.

You get the default configuration from CRA (which is hidden from you for focusing on coding). Add such file if you want to override it (you can also extend it, check the docs).


It's very useful to understand what eslint actually is and how we use it React development, check out related question "Do React hooks really have to start with “use”?".

Seasick answered 7/1, 2020 at 17:17 Comment(11)
Need to integrate it with extensions and settings via settings.jsonSeasick
If you open a console in DEBUG mode in vscode, you can check the eslint tab see it logs (after fixing errors you will get linting enabled)Seasick
I think you struggling to integrate it with vscode, why to downvote?Seasick
Sadly, none of the things you write help my situation. I don't have yarn, so I still cannot run eslint, and after creating a couple new projects just the way you stated, opening up those projects in VS Code still results in an empty "Output" console. Thank you for your efforts, though.Wheelbase
As I said, you need to integrate it with vscode... Cheers. And "I don't have yarn, so I still cannot run eslint", you can run it however you want, it will workSeasick
Regarding the downvote: Trying to earn easy points by doing one second of googling, and then posting the first link that comes up as an answer -- that's just lazy, insulting, and should not be rewarded. Now that you revised your answer and actually spent some time trying to help me, I will vote your answer back up. Once it actually solves my problem, I will of course accept it as the answer. :)Wheelbase
How did you integrate it? The docs that you shared the link to say that I just have to install and enable the ESLint plugin for VSCode -- I did. Also, I tried npm eslint ., and it complained that it didn't know about eslint.Wheelbase
Well.. you need to install eslint globally for npm eslint to work, and obviously I can't guess how you integrated it... Which steps you took... What are your vscode settings... Its an entirely new question.Seasick
So how do I "integrate it with VS Code"? Since it normally picks up any present ESLint configuration, having to manually wire it up is not straightforward.Wheelbase
No matter what I added to eslintConfig, I cannot alter the built-in rules. Have you actually been able to do so?Breaststroke
Be sure you dont have other eslint file which overrides it, and try openning a question. And yes, it works for me.Seasick
H
48

To expand on the top comment's answer:

...ESLint does not seem to be a dependency within package.json.

Why should it be? That's why you using a starter like CRA. It's an inner dependency, you don't need to worry about it, that's CRA's job.

A project created with create-react-app will have react-scripts as a dependency.

react-scripts has eslint installed as a dependency, as seen in react-scripts package.json.

You can see if a package is installed (and where) by running npm ls <package> in your project root.

npm ls eslint shows:

└─┬ [email protected]
  └── [email protected] 

This shows the dependency tree that we manually investigated by looking in GitHub at react-scripts.

So - a project made with create-react-app does come with eslint. As it is a dependency, not something globally installed, then it must be ran with a npm script.

This is why running eslint . in your terminal does not work, but using

    "lint": "eslint .",

then npm run lint does. (though you may with to make the command eslint --ignore-path .gitignore . due to a current bug).

Similarly, the eslint configs are installed in react-scripts, then referenced in the default project output's own package.json.

Helminthology answered 2/3, 2021 at 11:34 Comment(0)
S
20

Every Create React App depends on ESLint via react-scripts

I've answered most of your questions. Here is a summary.
(For more details, see Sections 1-6 below.)

Do projects generated by create-react-app come with some kind of ESLint configuration[?]

Yes, ESLint gets installed and configured.
(Sections 1, 4, 6 below.)

how do I enable and extend it correctly?

It is already enabled. You expand it exactly as you already suggested in the question, except that you don't need to change anything under the extends property.
(Sections 1, 4, 6 below.)

ESLint is obviously integrated into Create React App in a different way than it would be if it had been manually added to the project
[using npm install eslint --save-dev and npm init @eslint/config ?]

Both yes and no.
Installing ESLint once again (npm install eslint --save-dev) does add
  "devDependencies": {
    "eslint": "^7.32.0"
  }
to package.json. But that doesn't make any difference, because "eslint": "^7.32.0" is already installed as a dependency via react-scripts.
The react-scripts package includes the eslint-config-react-app package, which you don't get by installing ESLint separately. This package is specifically aimed at ReactJS applications.
It cannot be used for React Native applications, for example.
(Sections 1, 4, 6 below.)

one cannot run the eslint command in the project root [?]

Yes, you can! 1
It's npx eslint **/*.js
(Section 2 below.)

ESLint does not seem to be a dependency within package.json [?]

Yes, it is!
The dependency is indirect, as react-scripts depends on ESLint, among other packages.
(Section 1 below.)

VS Code doesn't pick up that there is ESLint present [?]

Yes, it does! Run npx eslint **/*.js.
If you get at least one warning or error, then you know you should see it in VS Code as well.
(Sections 3 & 5 below – check out the gotchas.)

there is no .eslintrc.* file in the project root.

If you have an eslintConfig property in package.json, then you don't need any additional configuration files for ESLint.
(Section 6 below.)

0. Prerequisites

To be able to answer your questions, I created an App : 2

npx create-react-app how-is-eslint-integrated-into-create-react-app

I then deleted all files in the src subdirectory, and inserted my own versions of App.js, App.css, index.js, and index.css, along with a components subdirectory that contains a Button component.

In package.json I deleted a few irrelevant lines, such as "version": "0.1.0",
and "private": true, and the production property under browserslist.

package.json :

{
  "name": "how-is-eslint-integrated-into-create-react-app",
  "dependencies": {
    "@testing-library/jest-dom": "^6.1.4",
    "@testing-library/react": "^14.1.0",
    "@testing-library/user-event": "^14.5.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^3.5.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": ["react-app", "react-app/jest"]
  },
  "browserslist": {
    "development": ["last 1 chrome version"]
  },
  "overrides":{
    "@babel/traverse": "^7.23.2",
    "nth-check": "^2.1.1",
    "postcss": "^8.4.31"
  }
}

You can download the resulting zip file containing all the necessary project files.

Once downloaded – from the root of the project (directory 59633005) – run npm install.
Expect it to take any time between 1 and 11 minutes to complete.

Next run npm start.
Expect your default web browser to open and – after you press F12 – display :

'npm start' opens the App in the default web browser

As you can see – no errors and no warnings in the console.
Now close the server from the terminal by pressing Ctrl+C.

Take a look inside App.js. The contents are :

// App.js
import React, { useCallback, useState } from 'react';
import "./App.css";
import Button from "./components/UI/Button/Button"

function App(unUsedArgument) {
  const [unUsedVariable, setShowParagraph] = useState(true);
  const showParagraphFcn = useCallback(() => {
    setShowParagraph((prevToggle) => !prevToggle);
  },[]);
  console.log("App RUNNING");
  return (
    <div className="app">
      <h1>Hi there!</h1>
      <Button onClick={showParagraphFcn}>A Button</Button>
    </div>
  );
}
export default App;

I now have a working project to help answer your questions.

1. ESLint is a dependency of react-scripts in package.json

VS Code does not seem to recognize that there is any kind of linter present/configured. This is not super surprising, as ESLint is not a dependency of the React project I just generated […]

The npx create-react-app ... does indeed install ESLint.

ESLint is deeply buried in the dependency tree of the react-scripts package.
The top node for ESLint in react-scripts is eslint-config-react-app. 3

Some basic configuration comes with it. So ESLint should work out of the box.

2. Run ESLint in the command line – the fastest way to check if it works

For starters: How do I run it?

Answer: 4

npx eslint **/*.js

1 warning when running ESLint from the command line

The warning in text:

7:10 warning 'unUsedVariable' is assigned a value but never used  no-unused-vars

– In less than 10 seconds, you get the same information on errors and warnings as in VS Code.

3. ESLint in Visual Studio Code

VS Code shows a warning for unUsedVariable on line 7 of App.js
(but for some reason not for unUsedArgument on line 6).

In VS Code, expect to see :

ESLint works out of the box for Create React App. 1 warning in VS Code.

4. How to expand the configuration of ESLint

How do I expand [ESLint in a Create React App]?

To expand ESLint, you need to add for example rules under eslintConfig in package.json, exactly as you have already suggested in your question.

To try your example, replace

,
  "eslintConfig": {
    "extends": ["react-app", "react-app/jest"]
  }

with

,
  "eslintConfig": {
    "extends": ["react-app", "react-app/jest"],
    "rules": {
      "semi": ["error", "always"],
      "quotes": ["error", "double"]
    }
  }

After restarting VS Code, it still shows the warning for unUsedVariable on line 7, but now also an error on line 2 for having single quotes instead of double quotes, and an error on line 4 for the missing semicolon at the end of the line.

With ESLint rules set, VS Code shows a warnings and errors

This shows that you have already correctly expanded Create React App.

Here is another example on how you may add rules in package.json | eslintConfig.

5. Some gotchas with VS Code

Still don't see the errors and warnings in VS Code?

  • You must install the VS Code ESLint extension.
  • Your local installation of Create React App installs ESLint locally. Installing ESLint globally is not recommended. If you did that, run npm uninstall eslint --global.
  • After you have made any changes to the "eslintConfig" property in package.json, you must close and restart VS Code.
    Then wait at least 60–100 seconds (or even 2 minutes) before you conclude it didn't work.

6. ESLint is configured in package.json

By default, every Create React App configures ESLint under the eslintConfig property in package.json as described in Section 4 above.

You won't need any ESLint configuration files.

You can run npm init @eslint/config (or equivalently npx eslint --init), which is a command that creates a .eslintrc.* configuration file (where * stands for js or json).
If you run this command, you may also want to move all the contents of .eslintrc.* to package.json under eslintConfig, and then delete the (possibly problematic) .eslintrc.* file. 5

References


1 In the original version of this answer, I suggested a slightly different command, but npx eslint **/*.js works fine for the new eslint.config.js file (flat config) as well as for the old .eslintrc.* files.

2 I'm on Windows 10, but I expect all the commands provided here to work just as fine on both Linux and macOS – except where otherwise stated.

3 I got this information from npmgraph - visualize npm module dependencies.

4 Alternatively, use the first line below if you are on Microsoft Windows (backslashes).
Use the second line if you are on Linux or macOS (forward slashes).

node_modules\.bin\eslint **/*.js
node_modules/.bin/eslint **/*.js

5 At the time of writing, the command npm init @eslint/config cannot yet produce configurations in the new "flat config" style.

Sheffield answered 10/3, 2022 at 11:1 Comment(0)
D
0

your question makes perfect sense. I found that this works:

  • run ESLint in VS Code with 'npx eslint' (shows all the options) or also 'npx eslint .'
  • add a script to package.json "lint": "eslint ." and then use 'npm run lint'

I did not have a problem with integrating ESLint to VS Code. After installing VS Code extension for ESLint, I automatically see the warnings/errors in VS Code under Problems.

Donnelly answered 20/11, 2020 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.