UNPKG

27.3 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- `.lintstagedrc.mjs` or `lint-staged.config.mjs` file in ESM format
110 - the default export value should be a configuration: `export default { ... }`
111- `.lintstagedrc.cjs` or `lint-staged.config.cjs` file in CommonJS format
112 - the exports value should be a configuration: `module.exports = { ... }`
113- `lint-staged.config.js` or `.lintstagedrc.js` in either ESM or CommonJS format, depending on
114 whether your project's _package.json_ contains the `"type": "module"` option or not.
115- Pass a configuration file using the `--config` or `-c` flag
116
117Configuration 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. JavaScript files can also export advanced configuration as a function. See [Using JS configuration files](#using-js-configuration-files) for more info.
118
119#### `package.json` example:
120
121```json
122{
123 "lint-staged": {
124 "*": "your-cmd"
125 }
126}
127```
128
129#### `.lintstagedrc` example
130
131```json
132{
133 "*": "your-cmd"
134}
135```
136
137This config will execute `your-cmd` with the list of currently staged files passed as arguments.
138
139So, considering you did `git add file1.ext file2.ext`, lint-staged will run the following command:
140
141`your-cmd file1.ext file2.ext`
142
143## Filtering files
144
145Linter 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:
146
147- If the glob pattern contains no slashes (`/`), micromatch's `matchBase` option will enabled, so globs match a file's basename regardless of directory:
148 - **`"*.js"`** will match all JS files, like `/test.js` and `/foo/bar/test.js`
149 - **`"!(*test).js"`**. will match all JS files, except those ending in `test.js`, so `foo.js` but not `foo.test.js`
150- If the glob pattern does contain a slash (`/`), it will match for paths as well:
151 - **`"./*.js"`** will match all JS files in the git repo root, so `/test.js` but not `/foo/bar/test.js`
152 - **`"foo/**/\*.js"`** will match all JS files inside the`/foo`directory, so`/foo/bar/test.js`but not`/test.js`
153
154When matching, lint-staged will do the following
155
156- Resolve the git root automatically, no configuration needed.
157- Pick the staged files which are present inside the project directory.
158- Filter them using the specified glob patterns.
159- Pass absolute paths to the linters as arguments.
160
161**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).
162
163Also see [How to use `lint-staged` in a multi-package monorepo?](#how-to-use-lint-staged-in-a-multi-package-monorepo)
164
165### Ignoring files
166
167The 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.
168
169Consider 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.
170
171In 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).
172
173## What commands are supported?
174
175Supported are any executables installed locally or globally via `npm` as well as any executable from your \$PATH.
176
177> Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn't have it installed.
178
179`lint-staged` uses [execa](https://github.com/sindresorhus/execa#preferlocal) to locate locally installed scripts. So in your `.lintstagedrc` you can write:
180
181```json
182{
183 "*.js": "eslint --fix"
184}
185```
186
187Pass arguments to your commands separated by space as you would do in the shell. See [examples](#examples) below.
188
189## Running multiple commands in a sequence
190
191You 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.
192
193For example:
194
195```json
196{
197 "*.js": ["eslint", "prettier --write"]
198}
199```
200
201going to execute `eslint` and if it exits with `0` code, it will execute `prettier --write` on all staged `*.js` files.
202
203## Using JS configuration files
204
205Writing 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.
206
207If 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.
208
209If 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.
210
211### Function signature
212
213The function can also be async:
214
215```ts
216(filenames: string[]) => string | string[] | Promise<string | string[]>
217```
218
219### Example: Export a function to build your own matchers
220
221<details>
222 <summary>Click to expand</summary>
223
224```js
225// lint-staged.config.js
226import micromatch from 'micromatch'
227
228export default (allStagedFiles) => {
229 const shFiles = micromatch(allStagedFiles, ['**/src/**/*.sh'])
230 if (shFiles.length) {
231 return `printf '%s\n' "Script files aren't allowed in src directory" >&2`
232 }
233 const codeFiles = micromatch(allStagedFiles, ['**/*.js', '**/*.ts'])
234 const docFiles = micromatch(allStagedFiles, ['**/*.md'])
235 return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
236}
237```
238
239</details>
240
241### Example: Wrap filenames in single quotes and run once per file
242
243<details>
244 <summary>Click to expand</summary>
245
246```js
247// .lintstagedrc.js
248export default {
249 '**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`),
250}
251```
252
253</details>
254
255### Example: Run `tsc` on changes to TypeScript files, but do not pass any filename arguments
256
257<details>
258 <summary>Click to expand</summary>
259
260```js
261// lint-staged.config.js
262export default {
263 '**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit',
264}
265```
266
267</details>
268
269### Example: Run ESLint on entire repo if more than 10 staged files
270
271<details>
272 <summary>Click to expand</summary>
273
274```js
275// .lintstagedrc.js
276export default {
277 '**/*.js?(x)': (filenames) =>
278 filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`,
279}
280```
281
282</details>
283
284### Example: Use your own globs
285
286<details>
287 <summary>Click to expand</summary>
288
289It'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.
290
291```js
292// lint-staged.config.js
293import micromatch from 'micromatch'
294
295export default {
296 '*': (allFiles) => {
297 const codeFiles = micromatch(allFiles, ['**/*.js', '**/*.ts'])
298 const docFiles = micromatch(allFiles, ['**/*.md'])
299 return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
300 },
301}
302```
303
304</details>
305
306### Example: Ignore files from match
307
308<details>
309 <summary>Click to expand</summary>
310
311If for some reason you want to ignore files from the glob match, you can use `micromatch.not()`:
312
313```js
314// lint-staged.config.js
315import micromatch from 'micromatch'
316
317export default {
318 '*.js': (files) => {
319 // from `files` filter those _NOT_ matching `*test.js`
320 const match = micromatch.not(files, '*test.js')
321 return `eslint ${match.join(' ')}`
322 },
323}
324```
325
326Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be `!(*test).js`.
327
328</details>
329
330### Example: Use relative paths for commands
331
332<details>
333 <summary>Click to expand</summary>
334
335```js
336import path from 'path'
337
338export default {
339 '*.ts': (absolutePaths) => {
340 const cwd = process.cwd()
341 const relativePaths = absolutePaths.map((file) => path.relative(cwd, file))
342 return `ng lint myProjectName --files ${relativePaths.join(' ')}`
343 },
344}
345```
346
347</details>
348
349## Reformatting the code
350
351Tools 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.
352
353```json
354{
355 "*.js": "prettier --write"
356}
357```
358
359Prior 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.
360
361## Examples
362
363All 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.
364
365```json
366{
367 "name": "My project",
368 "version": "0.1.0",
369 "scripts": {
370 "my-custom-script": "linter --arg1 --arg2"
371 },
372 "lint-staged": {}
373}
374```
375
376In `.husky/pre-commit`
377
378```shell
379#!/usr/bin/env sh
380. "$(dirname "$0")/_/husky.sh"
381
382npx lint-staged
383```
384
385_Note: we don't pass a path as an argument for the runners. This is important since lint-staged will do this for you._
386
387### ESLint with default parameters for `*.js` and `*.jsx` running as a pre-commit hook
388
389<details>
390 <summary>Click to expand</summary>
391
392```json
393{
394 "*.{js,jsx}": "eslint"
395}
396```
397
398</details>
399
400### Automatically fix code style with `--fix` and add to commit
401
402<details>
403 <summary>Click to expand</summary>
404
405```json
406{
407 "*.js": "eslint --fix"
408}
409```
410
411This will run `eslint --fix` and automatically add changes to the commit.
412
413</details>
414
415### Reuse npm script
416
417<details>
418 <summary>Click to expand</summary>
419
420If you wish to reuse a npm script defined in your package.json:
421
422```json
423{
424 "*.js": "npm run my-custom-script --"
425}
426```
427
428The following is equivalent:
429
430```json
431{
432 "*.js": "linter --arg1 --arg2"
433}
434```
435
436</details>
437
438### Use environment variables with linting commands
439
440<details>
441 <summary>Click to expand</summary>
442
443Linting 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).
444
445For example, here is `jest` running on all `.js` files with the `NODE_ENV` variable being set to `"test"`:
446
447```json
448{
449 "*.js": ["cross-env NODE_ENV=test jest --bail --findRelatedTests"]
450}
451```
452
453</details>
454
455### Automatically fix code style with `prettier` for any format Prettier supports
456
457<details>
458 <summary>Click to expand</summary>
459
460```json
461{
462 "*": "prettier --ignore-unknown --write"
463}
464```
465
466</details>
467
468### Automatically fix code style with `prettier` for JavaScript, TypeScript, Markdown, HTML, or CSS
469
470<details>
471 <summary>Click to expand</summary>
472
473```json
474{
475 "*.{js,jsx,ts,tsx,md,html,css}": "prettier --write"
476}
477```
478
479</details>
480
481### Stylelint for CSS with defaults and for SCSS with SCSS syntax
482
483<details>
484 <summary>Click to expand</summary>
485
486```json
487{
488 "*.css": "stylelint",
489 "*.scss": "stylelint --syntax=scss"
490}
491```
492
493</details>
494
495### Run PostCSS sorting and Stylelint to check
496
497<details>
498 <summary>Click to expand</summary>
499
500```json
501{
502 "*.scss": ["postcss --config path/to/your/config --replace", "stylelint"]
503}
504```
505
506</details>
507
508### Minify the images
509
510<details>
511 <summary>Click to expand</summary>
512
513```json
514{
515 "*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged"
516}
517```
518
519<details>
520 <summary>More about <code>imagemin-lint-staged</code></summary>
521
522[imagemin-lint-staged](https://github.com/tomchentw/imagemin-lint-staged) is a CLI tool designed for lint-staged usage with sensible defaults.
523
524See 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.
525
526</details>
527</details>
528
529### Typecheck your staged files with flow
530
531<details>
532 <summary>Click to expand</summary>
533
534```json
535{
536 "*.{js,jsx}": "flow focus-check"
537}
538```
539
540</details>
541
542## Frequently Asked Questions
543
544### Can I use `lint-staged` via node?
545
546<details>
547 <summary>Click to expand</summary>
548
549Yes!
550
551```js
552import lintStaged from 'lint-staged'
553
554try {
555 const success = await lintStaged()
556 console.log(success ? 'Linting was successful!' : 'Linting failed!')
557} catch (e) {
558 // Failed to load configuration
559 console.error(e)
560}
561```
562
563Parameters to `lintStaged` are equivalent to their CLI counterparts:
564
565```js
566const success = await lintStaged({
567 allowEmpty: false,
568 concurrent: true,
569 configPath: './path/to/configuration/file',
570 cwd: process.cwd(),
571 debug: false,
572 maxArgLength: null,
573 quiet: false,
574 relative: false,
575 shell: false
576 stash: true,
577 verbose: false
578})
579```
580
581You can also pass config directly with `config` option:
582
583```js
584const success = await lintStaged({
585 allowEmpty: false,
586 concurrent: true,
587 config: { '*.js': 'eslint --fix' },
588 cwd: process.cwd(),
589 debug: false,
590 maxArgLength: null,
591 quiet: false,
592 relative: false,
593 shell: false,
594 stash: true,
595 verbose: false,
596})
597```
598
599The `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.
600
601</details>
602
603### Using with JetBrains IDEs _(WebStorm, PyCharm, IntelliJ IDEA, RubyMine, etc.)_
604
605<details>
606 <summary>Click to expand</summary>
607
608_**Update**_: The latest version of JetBrains IDEs now support running hooks as you would expect.
609
610When 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.
611
612Until the issue is resolved in the IDE, you can use the following config to work around it:
613
614husky v1.x
615
616```json
617{
618 "husky": {
619 "hooks": {
620 "pre-commit": "lint-staged",
621 "post-commit": "git update-index --again"
622 }
623 }
624}
625```
626
627husky v0.x
628
629```json
630{
631 "scripts": {
632 "precommit": "lint-staged",
633 "postcommit": "git update-index --again"
634 }
635}
636```
637
638_Thanks to [this comment](https://youtrack.jetbrains.com/issue/IDEA-135454#comment=27-2710654) for the fix!_
639
640</details>
641
642### How to use `lint-staged` in a multi-package monorepo?
643
644<details>
645 <summary>Click to expand</summary>
646
647Starting 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.
648
649If 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.
650[`lerna`](https://github.com/lerna/lerna) can be used to execute the `precommit` script in all sub-packages.
651
652Example repo: [sudo-suhas/lint-staged-multi-pkg](https://github.com/sudo-suhas/lint-staged-multi-pkg).
653
654</details>
655
656### Can I lint files outside of the current project folder?
657
658<details>
659 <summary>Click to expand</summary>
660
661tl;dr: Yes, but the pattern should start with `../`.
662
663By default, `lint-staged` executes linters only on the files present inside the project folder(where `lint-staged` is installed and run from).
664So this question is relevant _only_ when the project folder is a child folder inside the git repo.
665In 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.
666
667`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.
668Note that patterns like `*.js`, `**/*.js` will still only match the project files and not any of the files in parent or sibling directories.
669
670Example repo: [sudo-suhas/lint-staged-django-react-demo](https://github.com/sudo-suhas/lint-staged-django-react-demo).
671
672</details>
673
674### How can I ignore files from `.eslintignore`?
675
676<details>
677 <summary>Click to expand</summary>
678
679ESLint 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 ).
680
681#### ESLint < 7
682
683<details>
684 <summary>Click to expand</summary>
685
686Based 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.
687
688So you can setup a `.lintstagedrc.js` config file to do this:
689
690```js
691import { CLIEngine } from 'eslint'
692
693export default {
694 '*.js': (files) => {
695 const cli = new CLIEngine({})
696 return 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' ')
697 },
698}
699```
700
701</details>
702
703#### ESLint >= 7
704
705<details>
706 <summary>Click to expand</summary>
707
708In 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.
709
710Since [10.5.3](https://github.com/okonet/lint-staged/releases), any errors due to a bad ESLint config will come through to the console.
711
712```js
713import { ESLint } from 'eslint'
714
715const removeIgnoredFiles = async (files) => {
716 const eslint = new ESLint()
717 const isIgnored = await Promise.all(
718 files.map((file) => {
719 return eslint.isPathIgnored(file)
720 })
721 )
722 const filteredFiles = files.filter((_, i) => !isIgnored[i])
723 return filteredFiles.join(' ')
724}
725
726export default {
727 '**/*.{ts,tsx,js,jsx}': async (files) => {
728 const filesToLint = await removeIgnoredFiles(files)
729 return [`eslint --max-warnings=0 ${filesToLint}`]
730 },
731}
732```
733
734</details>
735
736</details>