Add Prettier to TypeScript Projects with PreCommit Hook

Where you been?

If you haven’t heard of Prettier you are missing out on one of the best tools for the javascript community. I’ve been hanging around on the outskirts of adopting Prettier because I’m very focused on TypeScript projects and initially there was no support for TypeScript. That was until 12 days ago when 1.4.0 was published. So now I’m diving head in on all projects to default with Prettier support. I’ll keep this brief, so let’s dive in.

The Steps

First, we need to add a few packages to our project as dev dependencies. Run the following from your terminal:

npm install prettier lint-staged husky --save-dev

You can use yarn if you’d like instead of npm to install the dev dependencies.

Second, open your project’s package.json and add the following script and object for lint-staged

"scripts": {
  "precommit": "lint-staged"
},
"lint-staged": {
  "*.ts": [
  "prettier --write",
  "git add"
 ]
},

That’s basically all you need to do. Pretty simple, our precommit script will run lint-staged which will run the prettier command on the .ts files being committed.