Github url


by okonet

🚫💩 — Run linters on git staged files

7.2K Stars 272 Forks Last release: 23 days ago (v10.2.11) MIT License 744 Commits 167 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

🚫💩 lint-staged GitHub Actions Build Status for Windows npm version Codecov

Run linters against staged git files and don't let :poop: slip into your code base!



Linting makes more sense when run before committing your code. By doing so you can ensure no errors go into the repository and enforce code style. But running a lint process on a whole project is slow and linting results can be irrelevant. Ultimately you only want to lint files that will be committed.

This project contains a script that will run arbitrary shell tasks with a list of staged files as an argument, filtered by a specified glob pattern.

Related blogs posts and talks

If you've written one, please submit a PR with the link to it!

Installation and setup

The fastest way to start using lint-staged is to run following command in your terminal:

npx mrm lint-staged

It will install and configure husky and lint-staged depending on code quality tools from


dependencies so please make sure you install (

npm install --save-dev

) and configure all code quality tools like Prettier, ESlint prior that.

Don't forget to commit changes to


to share this setup with your team!

Now change a few files,

git add


git add --patch

some of them to your commit and try to

git commit


See examples and configuration for more information.


See Releases



  • From
    onwards any new modifications to originally staged files will be automatically added to the commit. If your task previously contained a
    git add
    step, please remove this. The automatic behaviour ensures there are less race-conditions, since trying to run multiple git operations at the same time usually results in an error.
  • From
    onwards lint-staged uses git stashes to improve speed and provide backups while running. Since git stashes require at least an initial commit, you shouldn't run lint-staged in an empty repo.
  • From
    onwards lint-staged requires Node.js version 10.13.0 or later.
  • From
    onwards lint-staged will abort the commit if linter tasks undo all staged changes. To allow creating empty commit, please use the ```
  • -allow-empty

Command line flags

❯ npx lint-staged --help Usage: lint-staged [options] Options: -V, --version output the version number --allow-empty allow empty commits when tasks revert all staged changes (default: false) -c, --config [path] path to configuration file -d, --debug print additional debug information (default: false) --no-stash disable the backup stash, and do not revert in case of errors -p, --concurrent <parallel tasks> the number of tasks to run concurrently, or false to run
                                     tasks serially (default: true)
  -q, --quiet disable lint-staged’s own console output (default: false)
  -r, --relative pass relative filepaths to tasks (default: false)
  -x, --shell skip parsing of tasks for better shell support (default:
  -v, --verbose show task output even when tasks succeed; by default only
                                     failed output is shown (default: false)
  -h, --help display help for command
  • *```
  • -allow-empty ```**: By default, when linter tasks undo all staged changes, lint-staged will exit with an error and abort the commit. Use this flag to allow creating empty git commits.
  • *```
  • -config [path] ```**: Manually specify a path to a config file or npm package name. Note: when used, lint-staged won't perform the config file search and print an error if the specified file cannot be found.
  • *```
  • -debug
     - uses [debug]( internally to log additional information about staged files, commands being executed, location of binaries, etc. Debug logs, which are automatically enabled by passing the flag, can also be enabled by setting the environment variable 
     - uses [
    renderer]( for 
    listr ``` ; this causes serial, uncoloured output to the terminal, instead of the default (beautified, dynamic) output.
  • *```
  • -concurrent [number | (true/false)]
    : Run all tasks serially
    (default) : _Infinite_ concurrency. Runs as many tasks in parallel as possible.
    : Run the specified number of tasks in parallel, where 
    is equivalent to 
    false ``` .
  • *```
  • -no-stash ```**: By default a backup stash will be created before running the tasks, and all task modifications will be reverted in case of an error. This option will disable creating the stash, and instead leave all modifications in the index when aborting the commit.
  • *```
  • -quiet ```**: Supress all CLI output, except from tasks.
  • *```
  • -relative
    runs) to tasks. Default is 
    false ``` .
  • *```
  • -shell ```**: By default linter commands will be parsed for speed and security. This has the side-effect that regular shell scripts might not work as expected. You can skip parsing of commands with this option.
  • *```
  • -verbose


Starting with v3.1 you can now use different ways of configuring it:

  • lint-staged
    object in your
  • .lintstagedrc
    file in JSON or YML format
  • lint-staged.config.js
    file in JS format
  • Pass a configuration file using the ```
  • -config
  • c

See cosmiconfig for more details on what formats are supported.

Configuration should be an object where each value is a command to run and its key is a glob pattern to use for this command. This package uses micromatch for glob patterns.



{ "lint-staged": { "\*": "your-cmd" } }



{ "\*": "your-cmd" }

This config will execute


with the list of currently staged files passed as arguments.

So, considering you did

git add file1.ext file2.ext

, lint-staged will run the following command:

your-cmd file1.ext file2.ext

Filtering files

Linter commands work on a subset of all staged files, defined by a glob pattern. `lint-staged´ uses micromatch for matching files with the following rules:

  • If the glob pattern contains no slashes (
    ), micromatch's

    option will enabled, so globs match a file's basename regardless of directory:

  • ``` "\.js"


  • ``` "!(\test).js"
    , so 
    but not 
    foo.test.js ```
  • If the glob pattern does contain a slash (

    ), it will match for paths as well:

  • ``` "./\.js"
    but not 
     - **`"foo/**/\*.js"
    ** will match all JS files inside the
    directory, so
    but not

When matching,


will do the following

  • Resolve the git root automatically, no configuration needed.
  • Pick the staged files which are present inside the project directory.
  • Filter them using the specified glob patterns.
  • Pass absolute paths to the linters as arguments.



will pass absolute paths to the linters to avoid any confusion in case they're executed in a different working directory (i.e. when your


directory isn't the same as your



Also see [How to use


in a multi package monorepo?](

Ignoring files

The concept of


is to run configured linter (or other) tasks on files that are staged in git.


will always pass a list of all staged files to the task, and ignoring any files should be configured in the task itself.

Consider a project that uses [


]( to keep code format consistent across all files. The project also stores minified 3rd-party vendor libraries in the


directory. To keep


from throwing errors on these files, the vendor directory should be added to prettier's ignore configuration, the


file. Running

npx prettier .

will ignore the entire vendor directory, throwing no errors. When


is added to the project and configured to run prettier, all modified and staged files in the vendor directory will be ignored by prettier, even though it receives them as input.

In advanced scenarios, where it is impossible to configure the linter task itself to ignore files, but some staged files should still be ignored by


, it is possible to filter filepaths before passing them to tasks by using the function syntax. See Example: Ignore files from match.

What commands are supported?

Supported are any executables installed locally or globally via


as well as any executable from your $PATH.

Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn’t have it installed.


uses execa to locate locally installed scripts. So in your


you can write:

{ "\*.js": "eslint --fix" }

Pass arguments to your commands separated by space as you would do in the shell. See examples below.

Running multiple commands in a sequence

You can run multiple commands in a sequence on every glob. To do so, pass an array of commands instead of a single one. This is useful for running autoformatting tools like

eslint --fix



but can be used for any arbitrary sequences.

For example:

{ "\*.js": ["eslint", "prettier --write"] }

going to execute


and if it exits with


code, it will execute

prettier --write

on all staged



Using JS functions to customize tasks

When supplying configuration in JS format it is possible to define the task as a function, which will receive an array of staged filenames/paths and should return the complete command as a string. It is also possible to return an array of complete command strings, for example when the task supports only a single file input. The function can be either sync or async.

type TaskFn = (filenames: string[]) =\> string | string[] | Promise<string string>

Example: Wrap filenames in single quotes and run once per file

// .lintstagedrc.js module.exports = { '\*\*/\*.js?(x)': (filenames) =\> =\> `prettier --write '${filename}'`) }

Example: Run


on changes to TypeScript files, but do not pass any filename arguments

// lint-staged.config.js module.exports = { '\*\*/\*.ts?(x)': () =\> 'tsc -p tsconfig.json --noEmit' }

Example: Run eslint on entire repo if more than 10 staged files

// .lintstagedrc.js module.exports = { '\*\*/\*.js?(x)': (filenames) =\> filenames.length \> 10 ? 'eslint .' : `eslint ${filenames.join(' ')}` }

Example: Use your own globs

// lint-staged.config.js const micromatch = require('micromatch') module.exports = { '\*': (allFiles) =\> { const match = micromatch(allFiles, ['\*.js', '\*.ts']) return `eslint ${match.join(' ')}` } }

Example: Ignore files from match

If for some reason you want to ignore files from the glob match, you can use



// lint-staged.config.js const micromatch = require('micromatch') module.exports = { '\*.js': (files) =\> { // from `files` filter those \_NOT\_ matching `*test.js` const match = micromatch.not(files, '\*test.js') return `eslint ${match.join(' ')}` } }

Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be



Example: Use relative paths for commands

const path = require('path') module.exports = { '\*.ts': (absolutePaths) =\> { const cwd = process.cwd() const relativePaths = =\> path.relative(cwd, file)) return `ng lint myProjectName --files ${relativePaths.join(' ')}` } }

Reformatting the code

Tools like Prettier, ESLint/TSLint, or stylelint can reformat your code according to an appropriate config by running

prettier --write


eslint --fix


tslint --fix


stylelint --fix

. Lint-staged will automatically add any modifications to the commit as long as there are no errors.

{ "\*.js": "prettier --write" }

Prior to version 10, tasks had to manually include

git add

as the final step. This behavior has been integrated into lint-staged itself in order to prevent race conditions with multiple tasks editing the same files. If lint-staged detects

git add

in task configurations, it will show a warning in the console. Please remove

git add

from your configuration after upgrading.


All examples assuming you’ve already set up lint-staged and husky in the



{ "name": "My project", "version": "0.1.0", "scripts": { "my-custom-script": "linter --arg1 --arg2" }, "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": {} }

Note we don’t pass a path as an argument for the runners. This is important since lint-staged will do this for you.

ESLint with default parameters for




running as a pre-commit hook

{ "\*.{js,jsx}": "eslint" }

Automatically fix code style with


and add to commit

{ "\*.js": "eslint --fix" }

This will run

eslint --fix

and automatically add changes to the commit.

Reuse npm script

If you wish to reuse a npm script defined in your package.json:

{ "\*.js": "npm run my-custom-script --" }

The following is equivalent:

{ "\*.js": "linter --arg1 --arg2" }

Use environment variables with linting commands

Linting commands do not support the shell convention of expanding environment variables. To enable the convention yourself, use a tool like [



For example, here is


running on all


files with the


variable being set to



{ "\*.js": ["cross-env NODE\_ENV=test jest --bail --findRelatedTests"] }

Automatically fix code style with


for javascript, typescript, markdown, HTML, or CSS

{ "\*.{js,jsx,ts,tsx,md,html,css}": "prettier --write" }

Stylelint for CSS with defaults and for SCSS with SCSS syntax

{ "\*.css": "stylelint", "\*.scss": "stylelint --syntax=scss" }

Run PostCSS sorting and Stylelint to check

{ "\*.scss": ["postcss --config path/to/your/config --replace", "stylelint"] }

Minify the images

{ "\*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged" }
More about imagemin-lint-staged

imagemin-lint-staged is a CLI tool designed for lint-staged usage with sensible defaults.

See more on this blog post for benefits of this approach.

### Typecheck your staged files with flow
{ "\*.{js,jsx}": "flow focus-check" }

Frequently Asked Questions

Can I use


via node?


const lintStaged = require('lint-staged') try { const success = await lintStaged() console.log(success ? 'Linting was successful!' : 'Linting failed!') } catch (e) { // Failed to load configuration console.error(e) }

Parameters to


are equivalent to their CLI counterparts:

const success = await lintStaged({ allowEmpty: false, concurrent: true, configPath: './path/to/configuration/file', cwd: process.cwd(), debug: false, maxArgLength: null, quiet: false, relative: false, shell: false stash: true, verbose: false })

You can also pass config directly with



const success = await lintStaged({ allowEmpty: false, concurrent: true, config: { '\*.js': 'eslint --fix' }, cwd: process.cwd(), debug: false, maxArgLength: null, quiet: false, relative: false, shell: false, stash: true, verbose: false })



option configures chunking of tasks into multiple parts that are run one after the other. This is to avoid issues on Windows platforms where the maximum length of the command line argument string is limited to 8192 characters. Lint-staged might generate a very long argument string when there are many staged files. This option is set automatically from the cli, but not via the Node.js API by default.

Using with JetBrains IDEs (WebStorm, PyCharm, IntelliJ IDEA, RubyMine, etc.)

Update: The latest version of JetBrains IDEs now support running hooks as you would expect.

When using the IDE's GUI to commit changes with the


hook, you might see inconsistencies in the IDE and command line. This is known issue at JetBrains so if you want this fixed, please vote for it on YouTrack.

Until the issue is resolved in the IDE, you can use the following config to work around it:

husky v1.x

{ "husky": { "hooks": { "pre-commit": "lint-staged", "post-commit": "git update-index --again" } } }

husky v0.x

{ "scripts": { "precommit": "lint-staged", "postcommit": "git update-index --again" } }

Thanks to this comment for the fix!

How to use


in a multi package monorepo?

Starting with v5.0,


automatically resolves the git root without any additional configuration. You configure


as you normally would if your project root and git root were the same directory.

If you wish to use


in a multi package monorepo, it is recommended to install [


]( in the root package.json.[


]( can be used to execute the


script in all sub-packages.

Example repo: sudo-suhas/lint-staged-multi-pkg.

Can I lint files outside of the current project folder?

tl;dr: Yes, but the pattern should start with



By default,


executes linters only on the files present inside the project folder(where


is installed and run from). So this question is relevant only when the project folder is a child folder inside the git repo. In certain project setups, it might be desirable to bypass this restriction. See #425, #487 for more context.


provides an escape hatch for the same(

\>= v7.3.0

). For patterns that start with


, all the staged files are allowed to match against the pattern. Note that patterns like




will still only match the project files and not any of the files in parent or sibling directories.

Example repo: sudo-suhas/lint-staged-django-react-demo.

How can i ignore files from



ESLint throws out

warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override

warnings that breaks the linting process ( if you used


which is recommended ).

Based on the discussion from , it was decided that using the outlined scriptis the best route to fix this.

So you can setup a


config file to do this:

const { CLIEngine } = require('eslint') const cli = new CLIEngine({}) module.exports = { '\*.js': (files) =\> 'eslint --max-warnings=0 ' + files.filter((file) =\> !cli.isPathIgnored(file)).join(' ') }

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.