Auto-format Elm code with elm-format before commit

Ritesh Pillai

Ritesh Pillai

July 9, 2018

In one of our earlier posts we talked about how we set up prettier and rubocop to automatically format our JavaScript and Ruby code on git commit.

Recently we started working with Elm in a couple of our projects - APISnapshot and AceHelp.

Tools like prettier and rubocop have really helped us take a load off our mind with regards to formatting code. And one of the very first things we wanted to sort out when we started doing Elm was pretty printing our Elm code.

elm-format created by Aaron VonderHaar formats Elm source code according to a standard set of rules based on the official Elm Style Guide.

Automatic code formatting

Let's setup git hook to automatically take care of code formatting. We can achieve this much like how we did it in our previous post, using Husky and Lint-staged.

Let's add Husky and lint-staged as dev dependencies to our project. And for completeness also include elm-format as a dev dependency.

1npm install --save-dev husky lint-staged elm-format

Husky makes it real easy to create git hooks. Git hooks are scripts that are executed by git before or after an event. We will be using the pre-commit hook which is run after you do a git commit command but before you type in a commit message.

This way we can change and format files that's about to be committed by running elm-format using Husky.

But there is one problem here. The changed files do not get added back to our commit.

This is where Lint-staged comes in. Lint-staged is built to run linters on staged files. So instead of running elm-format on a pre-commit hook we would run lint-staged. And we can configure lint-staged such that elm-format is run on all staged elm files.

We can also include Prettier to take care of all staged JavaScript files too.

Lets do this by editing our package.json file.

1{
2  "scripts": {
3    "precommit": "lint-staged"
4  },
5  "lint-staged": {
6    "*.elm": ["elm-format --yes", "git add"],
7    "*.js": ["prettier --write", "git add"]
8  }
9}

All set and done!

Now whenever we do a git commit command, all our staged elm and JavaScript files will get properly formatted before the commit goes in.

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.