Bulletproof Js with pre-commit checks in your project


Probably, you had situations committing some stuff to the repository that should not be ever committed by any sane developer. As consequences are broken builds funky things on production or crying management running around.

Most of the problems can be solved for Js environment with ESLint and here I’ll make a quick overview of ESLint features.

What is ESLint?

ESLint is a tool that helps you to check how you do write your JavaScript code. Js is a dynamic language and has a numerous things that can happen, so developers need to be disciplined about writing good code that doesn’t produce bugs.

How would I use it?

First of all you need to install eslint npm package:

Then you need to create .eslintrc or add eslintConfig field to the package.json file in your project. It can be done with command:

ESLint configuration

Here you can find huge variety of rules which can be checked by ESLint. There are variables rules, predicting possible errors, style rules and much much more.

Personally, I usually use some predefined subset of rules which can point to obvious errors or some bad smelling code . On another hand if you specify too much rules in your config, you might sink in warning and errors shooting from any smallest code change.

So let’s take a look at some basic configuration of ESLint:

"ecmaFeatures": {
// here you can enable or disable some features of ES6
"blockBindings": true,
"forOf": true,
"jsx": true
"rules": { // here you specify the rules
"semi": 2 // number

Numbers at the rule name key has following meaning:

  • 0 — turn the rule off
  • 1 — turn the rule on as a warning (doesn’t affect exit code)
  • 2 — turn the rule on as an error (exit code is 1 when triggered)

So you can leave some things just as warnings, and fix them as you have time.

Also, you can just use recommended rules by just saying:

"extends": "eslint:recommended"

Run eslint on your code

Running is pretty simple:

eslint yourJsFiles.js

and then you will get results of the check according to the configured rules.

I want to make it happen on every commit!

To make this happen, you need to add pre-commit or pre-push hooks. I use Husky for my projects, you can add it by saying:

npm install husky --save-dev

and then you need to add few more lines to your package.json file:

"scripts": {
"lint": "eslint yourJsFiles.js",
"precommit": "npm run test && npm run lint",
"prepush": "npm run test && npm run lint",
"...": "..."

And it’s done! Yeah! Before each commit or push your code will be checked for good style; additionally you can run some tests to make your app even better quality.

Got a question?

Feel free to ask me on Twitter or Github.

Originally published at www.devartem.info.