Introduction
Are you tired of pushing code that breaks down during build phase because some linting check or typescript check had failed? Well worry not because this post is going to ensure it does not happen again.
Pre Requisites
We need certain packages in our project before starting -
yarn add -D husky lint-stage
Husky is going to run the commands we specify before the commit happens.
Initialising Husky
In your project's terminal, type
npx init husky
You will see that a folder with the name .husky
is created in your project's directory.
Editing Package.json
Add the following in the scripts
part of your package.json
"postinstall": "husky install",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"tsc": "tsc --noEmit"
Also add this after the scripts
part in package.json
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix"
]
},
in the end, your package.json
would like this
"scripts": {
"dev": "next dev -p 3001",
"devEnv": "cpy .env.dev .env",
"build": "next build",
"start": "next start",
"postinstall": "husky install",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"tsc": "tsc --noEmit"
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": [
"eslint --fix"
]
},
Editing the Pre-Commit file
There is a pre commit in the .husky
folder. We need to edit it and add the following
yarn tsc
yarn eslint
Testing
Now in your code, create an intentional Typescript error or an disobey an ESLint Rule. Now try to commit the file and you will get an error and the code won't be committed and you will get an error in the git logs.
Edit: If you still want to commit your code, do the following
git commit -m "commit regardless of errors" --no-verify
Conclusion
Viola, that's it, now you won't be able to commit code with typescript errors and linting errors anymore and hopefully your build will stop failing as often.
Top comments (2)
Great post! Another useful step that you can add in your pre commit hook is formatting (using prettier)
Great addition! We can fix the eslint checks as well!