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 acheive 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.

npm 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 commited 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.

{
  "scripts": {
   "precommit": "lint-staged"
  },
  "lint-staged": {
    "*.elm": [
      "elm-format --yes",
      "git add"
    ],
    "*.js": [
      "prettier --write",
      "git add"
    ]
  }
}

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.