Skip to content

Instantly share code, notes, and snippets.

@lehtu
Last active August 3, 2017 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lehtu/4273c0fcedc1be02610f983543bbcb4d to your computer and use it in GitHub Desktop.
Save lehtu/4273c0fcedc1be02610f983543bbcb4d to your computer and use it in GitHub Desktop.
Here is how-to guide for linting staged files while trying to commit

How to setup linting in pre-commit (only for staged files)

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

Testing

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.

Example of package.json

{
  ...,
  "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"
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment