Configure Pre-commit Hook Prettier in your React Application in 1 Minute

Mangabo Kolawole - Apr 20 '22 - - Dev Community

Code styling and formating are important when writing software. It's more important to make sure that your JavaScript code is readable, because well you can format the whole JavaScript code on one line.

Prettier is a code formatted compatible with languages such as JavaScript, HTML, CSS, YAML, Markdown and GraphQL, and a lot more.

It's also great if the formatting is done automatically, mostly when you are staging changes using git.

In the React project, install the following dependencies:

yarn add -D prettier
Enter fullscreen mode Exit fullscreen mode

After that, add the .prettierrc configuration file.

{
  "arrowParens": "always",
  "bracketSpacing": true,
  "embeddedLanguageFormatting": "auto",
  "htmlWhitespaceSensitivity": "css",
  "insertPragma": false,
  "jsxBracketSameLine": false,
  "jsxSingleQuote": true,
  "printWidth": 80,
  "proseWrap": "preserve",
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "useTabs": false
}
Enter fullscreen mode Exit fullscreen mode

If you are working with a team, make sure to agree on the rules of the configuration file.

Next, let's add husky which simplifies the setup to use run scripts on specific git hooks. Here's an example of the pre-commit git hook.

{
  "scripts": {
    "prepare": "husky install",
    "format": "prettier --write .",
    "test": "jest"
  },
  "devDependencies": {
    "husky": "^6.0.0",
    "jest": "^26.6.3",
    "precise-commits": "^1.0.2",
    "prettier": "^2.3.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

Create a directory called .husky and inside this directory add the following file called pre-commit

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

yarn precise-commits
Enter fullscreen mode Exit fullscreen mode

The yarn precise-commits will reformat the exact code and will only deal with code formatting with prettier.

And the configuration is done.

To test the configuration, try the following commands:

git add.
git commit -m 'test commit with husky'
Enter fullscreen mode Exit fullscreen mode

And Voilà.

Article posted using bloggu.io. Try it for free.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player