Adding husky and lint-staged to a TypeScript project

Alan Yang
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.


These instructions assume the project already has eslint and prettier installed and configured.

  1. Install husky and lint-staged
npm install --save-dev husky lint-staged
  1. Enable Git hooks
npx husky install
  1. Modify the package.json to have a type-check script (if one does not already exist)
npm pkg set scripts."type-check"="tsc -p tsconfig.json --noEmit --skipLibCheck"
  1. Modify the package.json to automatically have Git hooks enabled after install
npm pkg set scripts.prepare="husky install"
  1. Create a lint-staged.config.js file in the root directory and add the following code to run eslint and prettier for js,jsx,json,ts,tsx files:
module.exports = {
  '**/*.{js,jsx,json,ts,tsx}': ['eslint --fix', 'prettier --write'],
  1. Create a pre-commit file in the .husky folder and add the following code to run lint-staged on staged files:
. "$(dirname "$0")/_/"

npx lint-staged --config lint-staged.config.js
  1. Create a pre-push file in the .husky folder and add the following code to run type-check:
. "$(dirname "$0")/_/"

npm run type-check