2021-03-26
|~2 min read
|284 words
I’ve written several times before about using lint-staged
to automate linting of staged commits (here and here for example). Today, I had a variation on that problem: I wanted to catch any console.log
statements before committing them.
Recently, I’ve had a few change sets come back to me because I’d missed a console.log
in my review and included it in the commit. I find console.log
s quite helpful for quick testing and validating that my code is behaving as expected, but they shouldn’t ever be shipped. Fortunately these were caught during review, but I shouldn’t have wasted my colleagues’ time with this sort of thing! So, I automated it1.
The biggest challenge I had was that I wanted to allow console logs during development, but then root them out before committing. The solution was to have multiple config files. ESLint has excellent documentation on the topic, but the crux of the idea is that one config file can extend another.
module.exports = {
// ... default rules
}
module.exports = {
extends: "./.eslintrc.js",
// new rules specific to staging
}
From here, I can configure lint staged as usual while adding a line to my new .eslint.staged.js
file for the appropriate file types. For example:
{
"scripts": {
"lint": "eslint ./src"
},
"lint-staged": {
"src/**/*.{js,json,md,tsx?}": ["eslint -c ./.eslintrc.staged.js"]
}
}
During development, I can get quick feedback with my yarn lint
script which will use the default .eslintrc.js
file, but before committing, I’ll now get the benefits of the .staged
variant!
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!