Adding husky and lint-staged to a TypeScript project

Alan Yang
April 7, 2023 - 2 min read
The combination of husky and lint-staged is a powerful way to automate code quality checks and enforce best practices in a project.
Below are the steps to add a pre-commit
hook that will lint and format staged files before they are committed and a pre-push
hook that will type-check the project before pushing.
Table of Contents
What is husky?
husky is a tool that allows users to add Git hooks to their project. Git hooks are scripts that run automatically when certain events occur, such as committing or pushing code.
What is lint-staged?
lint-staged is a tool that allows users to run linters, formatters, or any other command on specific files that are staged in Git, before they are committed.
Instructions
These instructions assume the project already has eslint and prettier installed and configured.
- Install husky and lint-staged
npm install --save-dev husky lint-staged
- Enable Git hooks
npx husky install
- Modify the
package.json
to have atype-check
script (if one does not already exist)
npm pkg set scripts."type-check"="tsc -p tsconfig.json --noEmit --skipLibCheck"
- Modify the
package.json
to automatically have Git hooks enabled after install
npm pkg set scripts.prepare="husky install"
- Create a
lint-staged.config.js
file in the root directory and add the following code to runeslint
andprettier
forjs,jsx,json,ts,tsx
files:
module.exports = {
'**/*.{js,jsx,json,ts,tsx}': ['eslint --fix', 'prettier --write'],
};
- Create a
pre-commit
file in the.husky
folder and add the following code to runlint-staged
on staged files:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged --config lint-staged.config.js
- Create a
pre-push
file in the.husky
folder and add the following code to runtype-check
:
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run type-check