Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable eslint only for edited files

Recently, I configured eslint one of my projects. This project was consisting of hundreds of files, as soon as I configured eslint starts showing errors in all files.

IMO, eslint traverses through all js files, which is not required currently. Is there any way we can limit eslint only for edited files?

like image 374
shekhardtu Avatar asked Feb 04 '19 06:02

shekhardtu


2 Answers

The answer is: do not run Eslint globally for all files. I think what you want is to prevent the offending code to be commited to repository (of cause, it's already there, commited before linting was introduced, but you want to prevent new commits to be made that contain eslint errors).
This means that it makes sense to run Eslint only on those files, that have changes in them and are about to be commited to repo, i.e. staged files. There is a package that does exactly that, lint-staged. In your package.json, you add a configuration like this:

"scripts": {
  "lint": "eslint --fix",
},
"lint-staged": {
  "*.{js,mjs,cjs,jsx,ts,tsx,vue}": [
     "npm run lint"
  ]
}

Then when you run npm run lint-staged, only the files that are staged will be passed as argument to lint command, so only those will be linted. Usually it makes sense to combine lint-staged with husky to automatically run linting and some other checks like formatting as a pre-commit hook (i.e. each time when you try to make a commit those checks will be executed) This way you can make sure that no code that contains errors will be commited.

like image 197
Yaroslav Larin Avatar answered Sep 18 '22 16:09

Yaroslav Larin


  1. If you want to lint staged and edited files, use:

    eslint $(git diff --name-only HEAD | grep -E '\.(js|jsx)$' | xargs)
    

    or run it with yarn if you want to use it in the terminal:

    yarn run eslint $(git diff --name-only HEAD | grep -E '\.(js|jsx)$' | xargs)
    

    Explanation:

    • git diff --name-only HEAD: name of edited files
    • grep -E '\.(js|jsx)$': Filter js and jsx files. You can add your file formats here.
    • xargs: get names as arguments
  2. Also you can use lint-staged library to lint staged files. It's useful if you want to run it before each commit and make sure your repo always remains pretty and linted.
    Read more about it here.

  3. If you want to lint last committed files, use:

    eslint $(git diff --name-only HEAD HEAD~1 | grep -E '\.(js|jsx)$' | xargs)
    
like image 28
Reza Mohammadi Avatar answered Sep 18 '22 16:09

Reza Mohammadi