Hello folks. I hope you all are doing well.
In this post, we will talk about how you can setup Husky pre-commit hook with ESLint, Prettier and lint-staged to avoid bad commits and properly format code before committing. So let's get into it.
Husky lets us run commands or script before committing or pushing our code to git.
ESLint is a tool that can analyze our code and find errors in that code using ESLint rules. It can also fix some errors on its own.
Prettier is an opinionated code formatter that can format our code with the help of rules that you set or defaults are used.
lint-staged can run multiple linters against staged git files which in our case are ESLint and Pretttier.
Setup new React or React Native project.
For React use
npx create-react-app demo
For React Native use
npx react-native init demo
npm install --save-dev husky lint-staged eslint eslint-config-airbnb prettier
yarn add --dev husky lint-staged eslint eslint-config-airbnb prettier
Here we are saving these modules as devDependencies to specify that these are only required in the development and not in runtime. I am using Airbnb's pre config file for ESLint. You can also go plain if you want to setup all ESLint rules by your self.
Replace or create .eslintrc.js file with the following code.
Replace or create .prettierrc.js file with the following code.
Open your package.json file and add the code that I have specified at the same level as dependencies.
The above code will run Prettier and ESLint rules against all js,jsx,ts,tsx files in the src directory. You can also specify more file extensions or you can write a script for a specific folder you want.
So yeah that's it. Now when you will try to commit any changes, ESLint and Prettier rules will execute and it will give you errors if there are any and stop you from causing any bad commits.
At BoTree Technologies, we build web and mobile applications to add value to our client’s business. We align ourselves to ensure that our client benefits the most out of our engagement.
Drop us a line to discuss how can we help take your business to the next level. Reach out to learn more about the software development companies in NYC for the various ways to improve or build the quality of projects and across your company.