Beginner’s Guide to Setting up Prettier Git Hooks

Andrew Salcedo
2 min readApr 3, 2018

--

Whether working in a global remote team or alone on your personal projects, it’s always a good idea to have nicely formatted code. But, with so many other decisions to make regarding your app, no one wants to waste energy, time, and keystrokes arguing about spaces or tabs, double quotes or single quotes, semi-colons or not. That’s where Prettier can really save you time and energy.

Prettier is a opinionated code formatter supporting many languages and most text editors.

Now, if Prettier has support in most text editors, couldn’t I just install the appropriate text editor plugin and be on my way?

True. I suppose you could. But, with time spent on each team member configuring their editor and possible hiccups along the way, it’s best to avoid any potential headaches and save time.

A simple git hook for only staged files — files that you changed for your commit — could ensure that code is properly formatted before committing. This would really help your team with keeping a standardized code format across your app, and you don’t even have to think about it. That’s a simple win.

Git Hooks

Git Hooks are scripts that Git executes before or after events such as: commit, push, and receive.

So for your app you’ll have to install Prettier, pretty-quick, and husky packages.

Yarn:

yarn add --dev prettier pretty-quick husky

NPM:

npm install --save-dev prettier pretty-quick husky

Now those packages should be in your devDependencies in your package.json file.

"devDependencies": {  "husky": "^0.14.3",  "prettier": "^1.11.1",  "pretty-quick": "^1.4.1"}

Once installed you’ll want to add a precommit git hook to your scripts in package.json.

"scripts": {  "precommit": "pretty-quick --staged"}

Now make some obnoxious changes to your code in some of your files, commit them, and you’ll see pretty quick & prettier do its magic. You should see something like this after sending your commit message.

husky > npm run -s precommit (node v8.11.1)🔍  Finding changed files since git revision 50866be.
🎯 Found 2 changed files.
✍️ Fixing up client/src/App.js.
✅ Everything is awesome!
[pretty-quick b711e76] messy code in app.js
1 file changed, 1 insertion(+), 1 deletion(-)

Set It and Forget It

This is a very simple way to ensure your team’s code is formatted and readable, and the fact that there isn’t much effort involved is a win for everybody.

Now you can focus your time on making more important decisions for your project.

Just remember when you think of Prettier & Git Hooks to…

kudos to those who remember this guy.

--

--

Andrew Salcedo

“Alex, I’ll take something clever for 250, please.”