UNPKG

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