DEV Community

Cover image for Configure Pre-commit Hook Prettier in your React Application in 1 Minute
Mangabo Kolawole
Mangabo Kolawole Subscriber

Posted on

6 1

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

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.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post