Credence Analytics - husky (eslint + prettier)

# Auto-verify your code before commit

 · 1 min read

husky (eslint + prettier)

# Auto-verify your code before commit

install some packages

npm install eslint --save-dev
eslint --init
npm install husky --save-dev
npm install lint-staged --save-dev
husky install
husky add .husky/pre-commit "npm run pretest"

Update your package.json

"scripts": {
    "prepare": "husky install",
    "pretest": "lint-staged"
},
"husky": {
    "hooks": {
        "pre-commit": "lint-staged"
    }
},
"lint-staged": {
    "*.js": [
        "prettier --write",
      "eslint --fix"
    ]
}

Here, if you do not want auto-fix eslint then remove "--fix" from lint-staged. eslint --fix will fix every rule violation it is capable of fixing, actually overwrite the code, and print out any warnings or errors it was incapable of fixing. Most errors are not actually automatically fixable.

Test it now...

  • create a sample file temp.js file in your project folder with some eslint errors

    tagline = "World";
    console.log(tagline);
    
  • Now, try to commit

    git add temp.js
    git commit -m "test husky"
    

    husky_1.png

  • You can also test it without commit statement

    git add temp.js
    npm test
    

    husky_2.png

    Just for reference, you can ignore it.

    • husky directory structure

    husky_3.png

    • npm test with no eslint error

      husky_4.png

    • git commit -m "test husky"with no eslint error

      husky_5.png

    • eslint --init just in case you need help here

      husky_6.png


No comments yet.

Add a comment
Ctrl+Enter to add comment