Skip to content

Instantly share code, notes, and snippets.

@nabeel-shakeel
Created August 4, 2022 06:54
Show Gist options
  • Save nabeel-shakeel/b8f1e8df57b1eb1d9b68285dec007a66 to your computer and use it in GitHub Desktop.
Save nabeel-shakeel/b8f1e8df57b1eb1d9b68285dec007a66 to your computer and use it in GitHub Desktop.
Husky and Lint Staged Setup

Husky - Pre-commit hook

This guide will walk you through the steps to setup git hooks (pre-commits, pre-push) using Husky. Additionally we will be using package lint-staged which tracks of staged code files and run jest tests related to those files on each commit. Let's set it up!

Install Packages

  • Install the following packages
npm install --save-dev husky lint-staged jest ts-jest @types/jest

Setup husky, lint-staged and jest

  • Add husky prepare script - Install husky on the root of project
npm set-script prepare "cd ../../ && husky install"
  • Run command
npm run prepare
  • Add pre-commit hook with command lint-staged - Run this command from the root of project
npx husky add .husky/pre-commit "npx lint-staged"
  • Create .lintstagedrc.json on the root of folder and add following content in it
{
  "src/**/*.{ts,tsx}": ["jest --bail --findRelatedTests"]
}
  • Create jest config file using command
npx ts-jest config:init
  • Add following content in jest.config.js created by above command
// eslint-disable-next-line no-undef
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  roots: ['<rootDir>/src/'],
}

Now add the test files and when you staged code files and try to commit, it will automatically run the related test before commmit!

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment