UNPKG

26.9 kBMarkdownView Raw
1# 🚫💩 lint-staged ![GitHub Actions](https://github.com/okonet/lint-staged/workflows/CI/badge.svg) [![npm version](https://badge.fury.io/js/lint-staged.svg)](https://badge.fury.io/js/lint-staged) [![Codecov](https://codecov.io/gh/okonet/lint-staged/branch/master/graph/badge.svg)](https://codecov.io/gh/okonet/lint-staged)
2
3Run linters against staged git files and don't let :poop: slip into your code base!
4
5[![asciicast](https://asciinema.org/a/199934.svg)](https://asciinema.org/a/199934)
6
7## Why
8
9Linting 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.
10
11This 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.
12
13## Related blog posts and talks
14
15- [Introductory Medium post - Andrey Okonetchnikov, 2016](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8#.8qepn2b5l)
16- [Running Jest Tests Before Each Git Commit - Ben McCormick, 2017](https://benmccormick.org/2017/02/26/running-jest-tests-before-each-git-commit/)
17- [AgentConf presentation - Andrey Okonetchnikov, 2018](https://www.youtube.com/watch?v=-mhY7e-EsC4)
18- [SurviveJS interview - Juho Vepsäläinen and Andrey Okonetchnikov, 2018](https://survivejs.com/blog/lint-staged-interview/)
19- [Prettier your CSharp with `dotnet-format` and `lint-staged`](https://blog.johnnyreilly.com/2020/12/prettier-your-csharp-with-dotnet-format-and-lint-staged.html)
20
21> If you've written one, please submit a PR with the link to it!
22
23## Installation and setup
24
25The fastest way to start using lint-staged is to run the following command in your terminal:
26
27```bash
28npx mrm@2 lint-staged
29```
30
31This command will install and configure [husky](https://github.com/typicode/husky) and lint-staged depending on the code quality tools from your project's `package.json` dependencies, so please make sure you install (`npm install --save-dev`) and configure all code quality tools like [Prettier](https://prettier.io) and [ESLint](https://eslint.org) prior to that.
32
33Don't forget to commit changes to `package.json` and `.husky` to share this setup with your team!
34
35Now change a few files, `git add` or `git add --patch` some of them to your commit, and try to `git commit` them.
36
37See [examples](#examples) and [configuration](#configuration) for more information.
38
39## Changelog
40
41See [Releases](https://github.com/okonet/lint-staged/releases).
42
43### Migration
44
45#### v12
46
47- Since `v12.0.0` _lint-staged_ is a pure ESM module, so make sure your Node.js version is at least `12.20.0`, `14.13.1`, or `16.0.0`. Read more about ESM modules from the official [Node.js Documentation site here](https://nodejs.org/api/esm.html#introduction).
48
49#### v10
50
51- From `v10.0.0` onwards any new modifications to originally staged files will be automatically added to the commit.
52 If your task previously contained a `git add` step, please remove this.
53 The automatic behaviour ensures there are less race-conditions,
54 since trying to run multiple git operations at the same time usually results in an error.
55- From `v10.0.0` onwards, lint-staged uses git stashes to improve speed and provide backups while running.
56 Since git stashes require at least an initial commit, you shouldn't run lint-staged in an empty repo.
57- From `v10.0.0` onwards, lint-staged requires Node.js version 10.13.0 or later.
58- From `v10.0.0` onwards, lint-staged will abort the commit if linter tasks undo all staged changes. To allow creating an empty commit, please use the `--allow-empty` option.
59
60## Command line flags
61
62```bash
63❯ npx lint-staged --help
64Usage: lint-staged [options]
65
66Options:
67 -V, --version output the version number
68 --allow-empty allow empty commits when tasks revert all staged changes
69 (default: false)
70 -c, --config [path] path to configuration file, or - to read from stdin
71 -d, --debug print additional debug information (default: false)
72 --no-stash disable the backup stash, and do not revert in case of
73 errors
74 -p, --concurrent <parallel tasks> the number of tasks to run concurrently, or false to run
75 tasks serially (default: true)
76 -q, --quiet disable lint-staged’s own console output (default: false)
77 -r, --relative pass relative filepaths to tasks (default: false)
78 -x, --shell [path] skip parsing of tasks for better shell support (default:
79 false)
80 -v, --verbose show task output even when tasks succeed; by default only
81 failed output is shown (default: false)
82 -h, --help display help for command
83```
84
85- **`--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.
86- **`--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 will print an error if the specified file cannot be found. If '-' is provided as the filename then the config will be read from stdin, allowing piping in the config like `cat my-config.json | npx lint-staged --config -`.
87- **`--debug`**: Run in debug mode. When set, it does the following:
88 - uses [debug](https://github.com/visionmedia/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 `$DEBUG` to `lint-staged*`.
89 - uses [`verbose` renderer](https://github.com/SamVerschueren/listr-verbose-renderer) for `listr`; this causes serial, uncoloured output to the terminal, instead of the default (beautified, dynamic) output.
90- **`--concurrent [number | (true/false)]`**: Controls the concurrency of tasks being run by lint-staged. **NOTE**: This does NOT affect the concurrency of subtasks (they will always be run sequentially). Possible values are:
91 - `false`: Run all tasks serially
92 - `true` (default) : _Infinite_ concurrency. Runs as many tasks in parallel as possible.
93 - `{number}`: Run the specified number of tasks in parallel, where `1` is equivalent to `false`.
94- **`--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.
95- **`--quiet`**: Supress all CLI output, except from tasks.
96- **`--relative`**: Pass filepaths relative to `process.cwd()` (where `lint-staged` runs) to tasks. Default is `false`.
97- **`--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. To use a specific shell, use a path like `--shell "/bin/bash"`.
98- **`--verbose`**: Show task output even when tasks succeed. By default only failed output is shown.
99
100## Configuration
101
102Starting with v3.1 you can now use different ways of configuring lint-staged:
103
104- `lint-staged` object in your `package.json`
105- `.lintstagedrc` file in JSON or YML format, or you can be explicit with the file extension:
106 - `.lintstagedrc.json`
107 - `.lintstagedrc.yaml`
108 - `.lintstagedrc.yml`
109- `lint-staged.config.js`, `.lintstagedrc.js`, or `.lintstagedrc.cjs` file in JS format
110- Pass a configuration file using the `--config` or `-c` flag
111
112See [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for more details on what formats are supported.
113
114Configuration 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](https://github.com/micromatch/micromatch) for glob patterns.
115
116#### `package.json` example:
117
118```json
119{
120 "lint-staged": {
121 "*": "your-cmd"
122 }
123}
124```
125
126#### `.lintstagedrc` example
127
128```json
129{
130 "*": "your-cmd"
131}
132```
133
134This config will execute `your-cmd` with the list of currently staged files passed as arguments.
135
136So, considering you did `git add file1.ext file2.ext`, lint-staged will run the following command:
137
138`your-cmd file1.ext file2.ext`
139
140## Filtering files
141
142Linter commands work on a subset of all staged files, defined by a _glob pattern_. lint-staged uses [micromatch](https://github.com/micromatch/micromatch) for matching files with the following rules:
143
144- If the glob pattern contains no slashes (`/`), micromatch's `matchBase` option will enabled, so globs match a file's basename regardless of directory:
145 - **`"*.js"`** will match all JS files, like `/test.js` and `/foo/bar/test.js`
146 - **`"!(*test).js"`**. will match all JS files, except those ending in `test.js`, so `foo.js` but not `foo.test.js`
147- If the glob pattern does contain a slash (`/`), it will match for paths as well:
148 - **`"./*.js"`** will match all JS files in the git repo root, so `/test.js` but not `/foo/bar/test.js`
149 - **`"foo/**/\*.js"`** will match all JS files inside the`/foo`directory, so`/foo/bar/test.js`but not`/test.js`
150
151When matching, lint-staged will do the following
152
153- Resolve the git root automatically, no configuration needed.
154- Pick the staged files which are present inside the project directory.
155- Filter them using the specified glob patterns.
156- Pass absolute paths to the linters as arguments.
157
158**NOTE:** `lint-staged` 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 `.git` directory isn't the same as your `package.json` directory).
159
160Also see [How to use `lint-staged` in a multi-package monorepo?](#how-to-use-lint-staged-in-a-multi-package-monorepo)
161
162### Ignoring files
163
164The concept of `lint-staged` is to run configured linter tasks (or other tasks) on files that are staged in git. `lint-staged` will always pass a list of all staged files to the task, and ignoring any files should be configured in the task itself.
165
166Consider a project that uses [`prettier`](https://prettier.io/) to keep code format consistent across all files. The project also stores minified 3rd-party vendor libraries in the `vendor/` directory. To keep `prettier` from throwing errors on these files, the vendor directory should be added to prettier's ignore configuration, the `.prettierignore` file. Running `npx prettier .` will ignore the entire vendor directory, throwing no errors. When `lint-staged` 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.
167
168In advanced scenarios, where it is impossible to configure the linter task itself to ignore files, but some staged files should still be ignored by `lint-staged`, it is possible to filter filepaths before passing them to tasks by using the function syntax. See [Example: Ignore files from match](#example-ignore-files-from-match).
169
170## What commands are supported?
171
172Supported are any executables installed locally or globally via `npm` as well as any executable from your \$PATH.
173
174> Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn't have it installed.
175
176`lint-staged` uses [execa](https://github.com/sindresorhus/execa#preferlocal) to locate locally installed scripts. So in your `.lintstagedrc` you can write:
177
178```json
179{
180 "*.js": "eslint --fix"
181}
182```
183
184Pass arguments to your commands separated by space as you would do in the shell. See [examples](#examples) below.
185
186## Running multiple commands in a sequence
187
188You 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` or `stylefmt` but can be used for any arbitrary sequences.
189
190For example:
191
192```json
193{
194 "*.js": ["eslint", "prettier --write"]
195}
196```
197
198going to execute `eslint` and if it exits with `0` code, it will execute `prettier --write` on all staged `*.js` files.
199
200## Using JS configuration file
201
202Writing the configuration file in JavaScript is the most powerful way to configure lint-staged (`lint-staged.config.js`, [similar](https://github.com/okonet/lint-staged/README.md#configuration), or passed via `--config`). From the configuration file, you can export either a single function or an object.
203
204If the `exports` value is a function, it will receive an array of all staged filenames. You can then build your own matchers for the files and return a command string or an array of command strings. These strings are considered complete and should include the filename arguments, if wanted.
205
206If the `exports` value is an object, its keys should be glob matches (like in the normal non-js config format). The values can either be like in the normal config or individual functions like described above. Instead of receiving all matched files, the functions in the exported object will only receive the staged files matching the corresponding glob key.
207
208### Function signature
209
210The function can also be async:
211
212```ts
213(filenames: string[]) => string | string[] | Promise<string | string[]>
214```
215
216### Example: Export a function to build your own matchers
217
218<details>
219 <summary>Click to expand</summary>
220
221```js
222// lint-staged.config.js
223const micromatch = require('micromatch')
224
225module.exports = (allStagedFiles) => {
226 const shFiles = micromatch(allStagedFiles, ['**/src/**/*.sh'])
227 if (shFiles.length) {
228 return `printf '%s\n' "Script files aren't allowed in src directory" >&2`
229 }
230 const codeFiles = micromatch(allStagedFiles, ['**/*.js', '**/*.ts'])
231 const docFiles = micromatch(allStagedFiles, ['**/*.md'])
232 return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
233}
234```
235
236</details>
237
238### Example: Wrap filenames in single quotes and run once per file
239
240<details>
241 <summary>Click to expand</summary>
242
243```js
244// .lintstagedrc.js
245module.exports = {
246 '**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`),
247}
248```
249
250</details>
251
252### Example: Run `tsc` on changes to TypeScript files, but do not pass any filename arguments
253
254<details>
255 <summary>Click to expand</summary>
256
257```js
258// lint-staged.config.js
259module.exports = {
260 '**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit',
261}
262```
263
264</details>
265
266### Example: Run ESLint on entire repo if more than 10 staged files
267
268<details>
269 <summary>Click to expand</summary>
270
271```js
272// .lintstagedrc.js
273module.exports = {
274 '**/*.js?(x)': (filenames) =>
275 filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`,
276}
277```
278
279</details>
280
281### Example: Use your own globs
282
283<details>
284 <summary>Click to expand</summary>
285
286It's better to use the [function-based configuration (seen above)](https://github.com/okonet/lint-staged/README.md#example-export-a-function-to-build-your-own-matchers), if your use case is this.
287
288```js
289// lint-staged.config.js
290const micromatch = require('micromatch')
291
292module.exports = {
293 '*': (allFiles) => {
294 const codeFiles = micromatch(allFiles, ['**/*.js', '**/*.ts'])
295 const docFiles = micromatch(allFiles, ['**/*.md'])
296 return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
297 },
298}
299```
300
301</details>
302
303### Example: Ignore files from match
304
305<details>
306 <summary>Click to expand</summary>
307
308If for some reason you want to ignore files from the glob match, you can use `micromatch.not()`:
309
310```js
311// lint-staged.config.js
312const micromatch = require('micromatch')
313
314module.exports = {
315 '*.js': (files) => {
316 // from `files` filter those _NOT_ matching `*test.js`
317 const match = micromatch.not(files, '*test.js')
318 return `eslint ${match.join(' ')}`
319 },
320}
321```
322
323Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be `!(*test).js`.
324
325</details>
326
327### Example: Use relative paths for commands
328
329<details>
330 <summary>Click to expand</summary>
331
332```js
333const path = require('path')
334
335module.exports = {
336 '*.ts': (absolutePaths) => {
337 const cwd = process.cwd()
338 const relativePaths = absolutePaths.map((file) => path.relative(cwd, file))
339 return `ng lint myProjectName --files ${relativePaths.join(' ')}`
340 },
341}
342```
343
344</details>
345
346## Reformatting the code
347
348Tools like [Prettier](https://prettier.io), 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.
349
350```json
351{
352 "*.js": "prettier --write"
353}
354```
355
356Prior 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.
357
358## Examples
359
360All examples assume you've already set up lint-staged in the `package.json` file and [husky](https://github.com/typicode/husky) in its own config file.
361
362```json
363{
364 "name": "My project",
365 "version": "0.1.0",
366 "scripts": {
367 "my-custom-script": "linter --arg1 --arg2"
368 },
369 "lint-staged": {}
370}
371```
372
373In `.husky/pre-commit`
374
375```shell
376#!/usr/bin/env sh
377. "$(dirname "$0")/_/husky.sh"
378
379npx lint-staged
380```
381
382_Note: we don't pass a path as an argument for the runners. This is important since lint-staged will do this for you._
383
384### ESLint with default parameters for `*.js` and `*.jsx` running as a pre-commit hook
385
386<details>
387 <summary>Click to expand</summary>
388
389```json
390{
391 "*.{js,jsx}": "eslint"
392}
393```
394
395</details>
396
397### Automatically fix code style with `--fix` and add to commit
398
399<details>
400 <summary>Click to expand</summary>
401
402```json
403{
404 "*.js": "eslint --fix"
405}
406```
407
408This will run `eslint --fix` and automatically add changes to the commit.
409
410</details>
411
412### Reuse npm script
413
414<details>
415 <summary>Click to expand</summary>
416
417If you wish to reuse a npm script defined in your package.json:
418
419```json
420{
421 "*.js": "npm run my-custom-script --"
422}
423```
424
425The following is equivalent:
426
427```json
428{
429 "*.js": "linter --arg1 --arg2"
430}
431```
432
433</details>
434
435### Use environment variables with linting commands
436
437<details>
438 <summary>Click to expand</summary>
439
440Linting commands _do not_ support the shell convention of expanding environment variables. To enable the convention yourself, use a tool like [`cross-env`](https://github.com/kentcdodds/cross-env).
441
442For example, here is `jest` running on all `.js` files with the `NODE_ENV` variable being set to `"test"`:
443
444```json
445{
446 "*.js": ["cross-env NODE_ENV=test jest --bail --findRelatedTests"]
447}
448```
449
450</details>
451
452### Automatically fix code style with `prettier` for any format Prettier supports
453
454<details>
455 <summary>Click to expand</summary>
456
457```json
458{
459 "*": "prettier --ignore-unknown --write"
460}
461```
462
463</details>
464
465### Automatically fix code style with `prettier` for JavaScript, TypeScript, Markdown, HTML, or CSS
466
467<details>
468 <summary>Click to expand</summary>
469
470```json
471{
472 "*.{js,jsx,ts,tsx,md,html,css}": "prettier --write"
473}
474```
475
476</details>
477
478### Stylelint for CSS with defaults and for SCSS with SCSS syntax
479
480<details>
481 <summary>Click to expand</summary>
482
483```json
484{
485 "*.css": "stylelint",
486 "*.scss": "stylelint --syntax=scss"
487}
488```
489
490</details>
491
492### Run PostCSS sorting and Stylelint to check
493
494<details>
495 <summary>Click to expand</summary>
496
497```json
498{
499 "*.scss": ["postcss --config path/to/your/config --replace", "stylelint"]
500}
501```
502
503</details>
504
505### Minify the images
506
507<details>
508 <summary>Click to expand</summary>
509
510```json
511{
512 "*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged"
513}
514```
515
516<details>
517 <summary>More about <code>imagemin-lint-staged</code></summary>
518
519[imagemin-lint-staged](https://github.com/tomchentw/imagemin-lint-staged) is a CLI tool designed for lint-staged usage with sensible defaults.
520
521See more on [this blog post](https://medium.com/@tomchentw/imagemin-lint-staged-in-place-minify-the-images-before-adding-to-the-git-repo-5acda0b4c57e) for benefits of this approach.
522
523</details>
524</details>
525
526### Typecheck your staged files with flow
527
528<details>
529 <summary>Click to expand</summary>
530
531```json
532{
533 "*.{js,jsx}": "flow focus-check"
534}
535```
536
537</details>
538
539## Frequently Asked Questions
540
541### Can I use `lint-staged` via node?
542
543<details>
544 <summary>Click to expand</summary>
545
546Yes!
547
548```js
549const lintStaged = require('lint-staged')
550
551try {
552 const success = await lintStaged()
553 console.log(success ? 'Linting was successful!' : 'Linting failed!')
554} catch (e) {
555 // Failed to load configuration
556 console.error(e)
557}
558```
559
560Parameters to `lintStaged` are equivalent to their CLI counterparts:
561
562```js
563const success = await lintStaged({
564 allowEmpty: false,
565 concurrent: true,
566 configPath: './path/to/configuration/file',
567 cwd: process.cwd(),
568 debug: false,
569 maxArgLength: null,
570 quiet: false,
571 relative: false,
572 shell: false
573 stash: true,
574 verbose: false
575})
576```
577
578You can also pass config directly with `config` option:
579
580```js
581const success = await lintStaged({
582 allowEmpty: false,
583 concurrent: true,
584 config: { '*.js': 'eslint --fix' },
585 cwd: process.cwd(),
586 debug: false,
587 maxArgLength: null,
588 quiet: false,
589 relative: false,
590 shell: false,
591 stash: true,
592 verbose: false,
593})
594```
595
596The `maxArgLength` 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.
597
598</details>
599
600### Using with JetBrains IDEs _(WebStorm, PyCharm, IntelliJ IDEA, RubyMine, etc.)_
601
602<details>
603 <summary>Click to expand</summary>
604
605_**Update**_: The latest version of JetBrains IDEs now support running hooks as you would expect.
606
607When using the IDE's GUI to commit changes with the `precommit` hook, you might see inconsistencies in the IDE and command line. This is [known issue](https://youtrack.jetbrains.com/issue/IDEA-135454) at JetBrains so if you want this fixed, please vote for it on YouTrack.
608
609Until the issue is resolved in the IDE, you can use the following config to work around it:
610
611husky v1.x
612
613```json
614{
615 "husky": {
616 "hooks": {
617 "pre-commit": "lint-staged",
618 "post-commit": "git update-index --again"
619 }
620 }
621}
622```
623
624husky v0.x
625
626```json
627{
628 "scripts": {
629 "precommit": "lint-staged",
630 "postcommit": "git update-index --again"
631 }
632}
633```
634
635_Thanks to [this comment](https://youtrack.jetbrains.com/issue/IDEA-135454#comment=27-2710654) for the fix!_
636
637</details>
638
639### How to use `lint-staged` in a multi-package monorepo?
640
641<details>
642 <summary>Click to expand</summary>
643
644Starting with v5.0, `lint-staged` automatically resolves the git root **without any** additional configuration. You configure `lint-staged` as you normally would if your project root and git root were the same directory.
645
646If you wish to use `lint-staged` in a multi package monorepo, it is recommended to install [`husky`](https://github.com/typicode/husky) in the root package.json.
647[`lerna`](https://github.com/lerna/lerna) can be used to execute the `precommit` script in all sub-packages.
648
649Example repo: [sudo-suhas/lint-staged-multi-pkg](https://github.com/sudo-suhas/lint-staged-multi-pkg).
650
651</details>
652
653### Can I lint files outside of the current project folder?
654
655<details>
656 <summary>Click to expand</summary>
657
658tl;dr: Yes, but the pattern should start with `../`.
659
660By default, `lint-staged` executes linters only on the files present inside the project folder(where `lint-staged` is installed and run from).
661So this question is relevant _only_ when the project folder is a child folder inside the git repo.
662In certain project setups, it might be desirable to bypass this restriction. See [#425](https://github.com/okonet/lint-staged/issues/425), [#487](https://github.com/okonet/lint-staged/issues/487) for more context.
663
664`lint-staged` 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.
665Note that patterns like `*.js`, `**/*.js` will still only match the project files and not any of the files in parent or sibling directories.
666
667Example repo: [sudo-suhas/lint-staged-django-react-demo](https://github.com/sudo-suhas/lint-staged-django-react-demo).
668
669</details>
670
671### How can I ignore files from `.eslintignore`?
672
673<details>
674 <summary>Click to expand</summary>
675
676ESLint 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 `--max-warnings=0` which is recommended ).
677
678#### ESLint < 7
679
680<details>
681 <summary>Click to expand</summary>
682
683Based on the discussion from [this issue](https://github.com/eslint/eslint/issues/9977), it was decided that using [the outlined script ](https://github.com/eslint/eslint/issues/9977#issuecomment-406420893)is the best route to fix this.
684
685So you can setup a `.lintstagedrc.js` config file to do this:
686
687```js
688const { CLIEngine } = require('eslint')
689
690const cli = new CLIEngine({})
691
692module.exports = {
693 '*.js': (files) =>
694 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' '),
695}
696```
697
698</details>
699
700#### ESLint >= 7
701
702<details>
703 <summary>Click to expand</summary>
704
705In versions of ESLint > 7, [isPathIgnored](https://eslint.org/docs/developer-guide/nodejs-api#-eslintispathignoredfilepath) is an async function and now returns a promise. The code below can be used to reinstate the above functionality.
706
707Since [10.5.3](https://github.com/okonet/lint-staged/releases), any errors due to a bad ESLint config will come through to the console.
708
709```js
710const { ESLint } = require('eslint')
711
712const removeIgnoredFiles = async (files) => {
713 const eslint = new ESLint()
714 const isIgnored = await Promise.all(
715 files.map((file) => {
716 return eslint.isPathIgnored(file)
717 })
718 )
719 const filteredFiles = files.filter((_, i) => !isIgnored[i])
720 return filteredFiles.join(' ')
721}
722
723module.exports = {
724 '**/*.{ts,tsx,js,jsx}': async (files) => {
725 const filesToLint = await removeIgnoredFiles(files)
726 return [`eslint --max-warnings=0 ${filesToLint}`]
727 },
728}
729```
730
731</details>
732
733</details>