Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

husky+lint-staged runs on unstaged files

I'm trying to add a pre-commit git hook that will run my linter only on touched (staged) files. My project is based on Create React App.

I added the following to my package.json:

  "scripts": {
    "lint": "eslint 'src/**/*.js'",
    "lintfix": "eslint 'src/**/*.js' --fix"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*": ["npm run lintfix --", "git add"]
  }

The reason I run it on "*" is because I'm expecting the script itself (lintfix) to enforce it's configuration (src/**/*.js).

The problem is that I'm getting plenty of eslint errors on my entire codebase and not only on staged files as I wished.

What's the configuration I need for running my eslint only on staged files?

like image 282
Haji Avatar asked Aug 13 '19 06:08

Haji


People also ask

What is lint-staged in package JSON?

Note: lint-staged discovers the closest configuration to each staged file, even if that configuration doesn't include any matching globs. Given these example configurations: // ./.lintstagedrc.json { "*.md": "prettier --write" } // ./packages/frontend/.lintstagedrc.json { "*.js": "eslint --fix" }

What is Lintstagedrc?

.lintstagedrcThis will run the commands I want to run when lint-staged is called from the husky hook. If you want to add --fix to the eslint command you can append it here. Be sure your prettier tool is setup to handle formatting afterward. { "*.+(js|jsx)":[ "eslint" ], "*.+(js|json|md)":[ "prettier --write" ] }


1 Answers

From lint-staged readme.md :

{ "*": "your-cmd" }

This config will execute your-cmd with the list of currently staged files passed as arguments.

So, considering you did git add file1.ext file2.ext, lint-staged will run the following command:

your-cmd file1.ext file2.ext

So looking at your package.json, you are running the following :

eslint 'src/**/*.js' --fix file1.js file2.js file3.js fileX.js... ....

You need to replace npm run lintfix -- by eslint --fix to first test if it works (it should), then adapt your lintfix command without the generic src/**/*.js regex.

like image 117
sebastienbarbier Avatar answered Sep 22 '22 13:09

sebastienbarbier