UNPKG

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