Git hooks for TSLint and Prettier

4th July 2018 - 1 minute

⚠️ Warning: Since writing this post Palantir have announced that they are deprecating TSLint in favour of ESLint, this article probably isn't the best thing to follow anymore 😁

Note 📝: This article assumes you have already got TSLint & Prettier set up and working in your project. If you haven't then check out my other article to find out how to do so.

So, you've got TSLint & Prettier set up in your project but now you want to ensure that only code that successfully passes these checks can be committed to the codebase. To do this we will make use of Git Hooks.

First of all let's install our dependencies:

# Yarn
yarn add -D lint-staged husky@next

# or

# NPM
npm install --save-dev lint-staged husky@next

Now we have our dependencies installed let's add some necessary configuration to our package.json file.

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,tsx}": "tslint --project tsconfig.json"
  }
}

That's it! Now it is time to test it out. Make some changes in your codebase that cause the linter to be unhappy and then try and commit them. If you see Husky run and then reject the changes then you are good to go, great job 🙌

If you run into any issues then feel free to contact me over on Twitter @lukehglazebrook!