Add Husky + Lint-staged to React (with Typescript)

Sear Cheulong
3 min readJun 25, 2022

--

I assume that you already have at least the basic knowledge of React and Git.

First Step

Let set up a React project with Typescript using the command create-react-app

npx create-react-app automate-prettier-eslint-with-husky --template typescript

Second Step

Now we can add git to our project. Here I use GitHub for this project.

Create an empty repository in Github, then you will be shown this screen.

Next, you can add git and push the first commit to the repository by using the command below,

git remote add origin https://github.com/cheulong/automate-prettier-eslint-with-husky.gitgit branch -M maingit push -u origin main

After committing, it will show like below:

Third Step

Add dependencies

yarn add -D husky lint-staged prettier
  • husky — for using git hooks.
  • lint-staged — for running the command before committing .
  • prettier — for formatting the code.

Create .prettierrc to add the formatting rule

Create .prettierignore to add the ignored folder

Add Eslint and Prettier command to your scripts:

  • eslint src to check the code warning and error.
  • prettier --write to format the code.
  • prettier --check . to check the code format.

Add lint-staged command to package.json

Last Step

Finally, we enable the git hook

npx husky install

Then, add command to pre-commit hook

npx husky add .husky/pre-commit "yarn lint-staged"

You will see a .husky folder

Note: You can also edit the pre-commit file

Now let’s test it

git add .
git commit -m"add husky lint-staged"

The code is automatically formatted.

Congratulations, you successfully add husky and lint-staged to your React project.

The repository for this article https://github.com/cheulong/automate-prettier-eslint-with-husky

--

--

Sear Cheulong
Sear Cheulong

Written by Sear Cheulong

Frontend Developer at Seven Peaks Software, looking to learn new thing and language enthusiast. ^^

Responses (1)