First we need to get list of staged files.
git status -s -uno
Then we want to limit it only to list of files.
git status -s -uno | grep -o -e '[a-zA-Z0-9_.-]*.js'
And then let's pass it to eslint.
./node_modules/eslint/bin/eslint.js $(git status -s -uno | grep -o -e '[a-zA-Z0-9_.-]*.js')
So here it is inside package.json scripts:
"scripts": {
"lint.staged": "./node_modules/eslint/bin/eslint.js $(git status -s -uno | grep -o -e '[a-zA-Z0-9_.-]*.js')",
},
Okay, now we can test it by running yarn lint.staged
or npm run lint.staged
.
Next we will install (pre-commit)[https://github.com/observing/pre-commit] package. Howevere first let's add settings for it:
"pre-commit": [
"lint.staged"
],
Here we tell pre-commit package to run lint.staged when someone tries to commit stuff.
Now we are finally ready to install the package: npm install --save-dev pre-commit
Create some .js file that you know to have some linting errors.
echo 'console.log ( asd + "abc" )' >> broken.js
git add broken.js
git commit -m 'this should fail'
If eslint finds any errors from staged files it will prevent commit and show the linting errors.
{
...,
"scripts": {
"lint.staged": "./node_modules/eslint/bin/eslint.js $(git status -s -uno | grep -o -e '[a-zA-Z0-9_.-]*.js')",
},
"devDependencies": {
"pre-commit": "^1.2.2"
},
"pre-commit": [
"lint.staged"
]
}