Search code examples
eslintpre-commit-hookpre-commithuskylint-staged

How do I get lint-staged working with Husky version 6


I try to use Husky's pre-commit and lint-staged.

Those are installed:

"husky": "^5.1.3",
"lint-staged": "^10.5.4",

In package.json I have:

"scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\" && exit 1",
    "lint": "eslint --ext .js,.jsx,.ts,.tsx src --color",
    "isready": "npm run format && npm run lint && npm run build"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "pre-push": "npm test",
    }
  },
  "lint-staged": {
    "./src/*.{js,jsx,ts,tsx}": [
      "npm run format",
      "npm run lint",
      "git add"
    ]
  },

If I run npm run lint, currently I have 2 problems (1 error, 1 warning). So when I run git commit, I don't expect to be able to commit, right? But I can proceed and finish the commit.

What's wrong?

Update:

I downgraded husky to 4.3.8:

"husky": "^4.3.8",
"lint-staged": "^10.5.4",

Inside package.json, in my scripts I have:

"prettier": "prettier '**/*.{js,jsx,ts,tsx}' --write",
"lint": "eslint --ext .js,.jsx,.ts,.tsx src --color",

And:

"husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.{ts,tsx,js,jsx}": [
      "npm run prettier",
      "npm run lint",
      "git add"
    ]
  },

When I do a commit, Husky is still not fired off. What's wrong?

Update 2: I couldn't get Husky 4 to work so I upgraded to version 6:

npm install husky@6 --save-dev \
  && npx husky-init \
  && npm exec -- github:typicode/husky-4-to-6 --remove-v4-config

Now it works fine.

The only thing I can't get to work is lint-staged.

  • I added the hook npx husky add .husky/pre-commit "lint-staged"

But then I get .husky/pre-commit: line 4: lint-staged: command not found? How do I get lint-staged working with Husky version 6?


Solution

  • Making lint-staged working with Husky version 6 by adding:

    // .husky/pre-commit
    npm run pre-commit
    

    and:

    // package.json
    {
      "scripts": {
        "pre-commit": "lint-staged"
      }
    }