Is this a right way to use husky + lint-staged?

Shawn Chen picture Shawn Chen · Aug 8, 2018 · Viewed 24.8k times · Source

I found numerous blogs (including the lint-staged doc) introducing such a way to use husky+ lint-staged as the following code defined in the package.json:

{
  "scripts": {
    "precommit": "lint-staged"
  },
  "lint-staged": {
    "src/**/*.js": ["prettier --write","eslint --fix", "git add"]
  }
}

Since there are errors that neither "prettier" nor "eslint --fix" can fix, how can we prevent bad commit by such a usage?

Answer

maiksensi picture maiksensi · Dec 7, 2018

You can indeed run multiple commands with lint-staged and if one of them fails, you will get the correct exit code as shown in the example below. This works via the new husky hooks system:

With a configuration like this in package.json:

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    },
},
"lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,json,css}": [
        "prettier --write",
        "eslint --fix src/",
        "tslint --fix --project .",
        "git add"
    ]
},

The configuration runs prettier, eslint and tslint - you would get the following error on linting problems:

husky > pre-commit (node v8.12.0)
  ↓ Stashing changes... [skipped]
    → No partially staged files found...
  ❯ Running linters...
   ❯ Running tasks for src/**/*.{js,jsx,ts,tsx,json,css}
      ✖ prettier --write
        eslint --fix src/
        tslint --fix --project .
        git add
✖ prettier --write found some errors. Please fix them and try committing again.
...
husky > pre-commit hook failed (add --no-verify to bypass)

The last line shows you that git's own pre-commit hook failed and thus your changed won't get commited (if they are not fixable).