NOTE: For a more up-to-date and exhaustive explaination about how to maintain code consistency and quality, in your app, see this blog post.

Do you want to enforce prettier & linting with a pre-commit hook on a typescript project?  Thanks to husky and lint-staged, this is pretty easy to do.  First, install them into your project:

yarn add husky lint-staged -D

Then, in your package.json file, just add the following:

  "scripts": {
    "lint": "eslint './**/*.{ts,tsx}'",
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "./**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
      "prettier --write",
      "yarn lint",
      "git add"
    ]
  },

This will ensure most of the files you care about are automtically "prettified".  Then, it will ensure all your .ts and .tsx files are checked for linting errors before any commit.

This is what it looks like when you run git commit on any staged files that match your criteria and have linting errors:

Screenshot showing the results of committing with a prettier and lint commit hook. It was expected to fail but did not.

Wait ... what?  It should have failed but didn't!  There is definitely a warning in the Index.tsx file.  This yarn lint output clearly shows the warning:

Output of the yarn lint command shows that the Index.tsx file has a linting warning.

The problem is that by default, ESLint does not actually fail on warnings.  The exit code is 0 instead of something else.  So, husky sees no failure and allows the commit to go through.  

The fix is to enforce failing on warnings.  Just modify the lint script using the --max-warnings flag like this:

"lint": "eslint './**/*.{ts,tsx}' --max-warnings 0",

Now, every time your app has a lint warning, the pre-commit hook will fail.

Pre-commit hook failing now because there is a linting warning