Automatically format your Apex on every commit

Charlie Jonas
Nov 13 · 2 min read

If you aren’t already using Prettier for Apex, I highly recommend you try it out. Even though it doesn’t always format exactly as I would, the consistency and convenience of auto-formatting makes it more than worth it.

prettier logo
prettier logo

It’s easy enough to set up vscode to format on save, but we can take this a step further by running prettier on the pre-commit hook. This will ensure that code is always formatted before being committed.

And since we already have a package.json in our project, setup is extremely simple:


  1. npm i -D husky pretty-quick
  2. In package.json add the following:
  3. Add “apexInsertFinalNewline”: false, to your .prettierrc config. (explanation)
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"

That’s it, We’re done!

husky is a tool that makes git hooks dead simple (as you can see) and pretty-quick allows you to run prettier on only staged files.

One more thing…

In order to keep a bunch of formatting changes out of your pull requests, I recommend running prettier one time for everything.

You can easily do so by running:
npx prettier — write 'src/**/*.{trigger,cls}' .

Keep in mind, this will likely change a bunch of lines in every single apex file. It’s probably best to wait until you don’t have any divergent branches, otherwise you might have a tough time dealing with merge conflicts.

Once you’ve done this, you will very rarely see a “formatting only” change in git again!

-Happy coding


Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade