Linting console.log statements pre-commit with eslint

Posted December 12th, 2016 by

I always review my code before committing, but oft-times I inevitably miss console.log statements in my JavaScript code. On the current project I'm working on standard is used for linting but it is not enforced and it doesn't complain about console.log as far as I can tell.

I've seen some solutions on the internet that grep files looking for console.log but I felt using eslint would be more extensible if I wanted to lint anything else in future. Here are the simple steps if you want to do the same:

Install eslint globally for ease of use: npm install -g eslint

Then all you need is some simple eslint configuration and a pre-commit hook.

Here's the configuration I used which supports my use of rest/spread operators and also JSX:

eslintrc.json

{
                "parserOptions": {
                    "ecmaVersion": 6,
                    "sourceType": "module",
                    "ecmaFeatures": {
                      "jsx": true,
                      "experimentalObjectRestSpread": true
                    }
                },
                "rules": {
                  "no-console": "error"
                }
              }
              

"no-console": "error" is the rule that will cause the linter to fail if you leave any console.log statements in your code. The other stuff is all specific to your project's JavaScript setup so check out configuring eslint if you want to know more.

I then added an .eslintignore file for things I wasn't worried about linting, for example:

.eslintignore

webpack/coverage
              

Finally you'll just need a file in hooks/pre-commit that is very simple:

eslint path/to/the/js
              

And that's it! when you go to commit, if you've left any console.log statements in your javascript the commit will fail and eslint will tell you where to look.