Setup Husky in "pre-commit" hooks with Git Version Control
Install Husky, which will manage the pre-commit hooks
npm i --dev husky
Now you can go ahead and install the lint-staged file, which manages the linting for your changes. Create a .lintstagedrc.js file and add the following snippet
module.exports = {
// Type check TypeScript files
'**/*.(ts|tsx)': () => 'yarn tsc --noEmit',
// Lint & Prettify TS and JS files
'**/*.(ts|tsx|js)': filenames => [
yarn eslint ${filenames.join(' ')},
yarn prettier --write ${filenames.join(' ')}
],
// Prettify only Markdown and JSON files
'**/*.(md|json)': filenames => yarn prettier --write ${filenames.join(' ')}
};
If you look closely, this module is looking for TypeScript and JavaScript files and prettifying them as mentioned in your .prettierrc.js configuration. This is the check that runs as a pre-commit — before committing to Git.
After setting up, there is one last piece that you need to do: set up a shell file that will run Husky. Create a file at the root as /.husky/pre-commit and add the following code
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm run lint-staged
This sets up your pre-commit. Now, try changing anything in your app to something wrong and committing the changes. Your pre-commit should run and show you an error indicating the line number and file.
Pre-commit hooks are a great practice if you work with a big team. They help you manage formatting and linting rules, as well as make sure everybody is on the same page. Without pre-commit hooks, you may run into many merge conflicts, especially since linters and code formatters work differently on different machines.