How to integrate lint-stage with Husky?

Viewed 1494

My package.json(shortened version)

  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "tsc": "tsc",
    "type-check": "tsc --project tsconfig.json --pretty --noEmit",
    "lint": "eslint --ext js,jsx,ts,tsx --fix"
  },
  "dependencies": {
    "@types/node": "^14.14.25",
    "@types/react": "^17.0.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react-hooks": "^4.2.0",
    "next": "^10.0.6",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "typescript": "^4.1.4"
  },  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,jsx,ts,tsx}": "eslint --cache --fix"
  }

I installed everything with npm(not yarn). When I added empty file and made a commit

git commit -m "test"
[main ca9db77] test
 1 file changed, 4 insertions(+)
 create mode 100644 pages/test.tsx

There was no lint-staging,so husky is not visible. How to fix this?

1 Answers

You have to install husky as DevDependencies

Then create a prepare script with husky install:

"scripts": {
    "dev": "next dev",
    "build": "cross-env NODE_ENV=production next build",
    "start": "next start",
    "lint": "eslint src --max-warnings=0",
    "typecheck": "tsc --project tsconfig.json --pretty --noEmit",
    "test": "jest",
    "test:watch": "yarn test --watch",
    "prepare": "husky install"
  }

and run it once: npm run prepare

Then, add a hook: npx husky add .husky/pre-commit "npm test"

Open .husky\pre-commit

And add npx --no-install lint-staged

Your file should look like this:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx --no-install lint-staged

On package.json create the lint-staged key, like you have done.

"lint-staged": {
    "src/**/*": [
      "yarn lint --fix",
      "tsc-files --noEmit --pretty",
      "yarn test --findRelatedTests --bail"
    ]
  },
Related