Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 647
Shawn Chen Avatar asked Aug 08 '18 13:08

Shawn Chen


1 Answers

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).

like image 54
maiksensi Avatar answered Sep 28 '22 04:09

maiksensi