How to config Git Hooks + ESLint

Amir Elemam
3 min readJun 11, 2019

Everyone makes mistakes! An undeclared variable here, a typo there and when we realize, we’ve committed code with silly syntax errors. I’ve done it, you’ve done it and I’m pretty sure that every coder out there has done it. Don’t feel bad, it’s human nature.

And then someone invented the linters. Linters run through your code and check if you forgot to close a bracket or didn’t declare a variable. But what if we could run a linter automatically when we commit code? It’s possible! Here’s how:

Install

1) Install Node.js, you can download it here.

2) Install Git, you can download it here.

Creating a project

Jump to the terminal and create a new project:

$ mkdir eslint_git_hooks # Creates a new folder with name “eslint_git_hooks”$ cd eslint_git_hooks # Enters the folder eslint_git_hooks$ npm init –y # Creates a new npm project$ git init # Initiate git in your eslint_git_hooks folder$ npm i –g eslint babel-eslint # Installs ESlint and Babel ESLint globally in your system

Now that we have the project structure, we need to add the project root.

You can download a .eslintrc file ready to accept ES6 from my gist, click here.

Now add it to eslint_git_hooks’ root. Your project structure should look like this:

eslit_git_hooks folder structure

Config Git Hooks

Git Hooks is the way Git fires scripts when some action is performed. In our example, we’re going to run ESLint before every commit, so if ESLint fails, the changes are not committed. This prevents us from committing undeclared variables, functions missing the closing curly braces and so on.

You can access Git Hooks folder from eslint_git_hooks root, with the following command:

$ cd .git/hooks

If you list the files, you’ll see that there’re many options, in our example, we’re going to use pre-commit.sample.

So, copy the file with the following command:

$ cp pre-commit.sample pre-commit

Open pre-commit file in your preferred text editor and let’s change two lines:

1) Optional: Comment out verification for trailing spaces

# exec git diff-index — check — cached $against — 

If you don’t do it, the linter will catch trailing spaces in all your files, including those inside the node_modules folder. You can prevent it from running against the node_module folder later.

2) Add the ESLint command at the end of the pre-commit file

eslint .

Testing

Before we can test, restart your terminal, so that the ESLint command will be available

$ exec bash

Now, every time you commit something, ESlint will run and warn you of issues in your code.

Demo

You can find a demo project here.

--

--