UNPKG

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