UNPKG

38.5 kBMarkdownView Raw
1# 🚫💩 lint-staged [![Test & Release](https://github.com/okonet/lint-staged/actions/workflows/push.yml/badge.svg)](https://github.com/okonet/lint-staged/actions/workflows/push.yml) [![Publish](https://github.com/okonet/lint-staged/actions/workflows/tag.yml/badge.svg)](https://github.com/okonet/lint-staged/actions/workflows/tag.yml) [![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#### v15
76
77- Since `v15.0.0` _lint-staged_ no longer supports Node.js 16. Please upgrade your Node.js version to at least `18.12.0`.
78
79#### v14
80
81- Since `v14.0.0` _lint-staged_ no longer supports Node.js 14. Please upgrade your Node.js version to at least `16.14.0`.
82
83#### v13
84
85- 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.
86- Version `v13.3.0` was incorrectly released including code of version `v14.0.0`. This means the breaking changes of `v14` are also included in `v13.3.0`, the last `v13` version released
87
88#### v12
89
90- 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).
91
92#### v10
93
94- From `v10.0.0` onwards any new modifications to originally staged files will be automatically added to the commit.
95 If your task previously contained a `git add` step, please remove this.
96 The automatic behaviour ensures there are less race-conditions,
97 since trying to run multiple git operations at the same time usually results in an error.
98- From `v10.0.0` onwards, lint-staged uses git stashes to improve speed and provide backups while running.
99 Since git stashes require at least an initial commit, you shouldn't run lint-staged in an empty repo.
100- From `v10.0.0` onwards, lint-staged requires Node.js version 10.13.0 or later.
101- 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.
102
103## Command line flags
104
105```
106❯ npx lint-staged --help
107Usage: lint-staged [options]
108
109Options:
110 -V, --version output the version number
111 --allow-empty allow empty commits when tasks revert all staged changes (default: false)
112 -p, --concurrent <number|boolean> the number of tasks to run concurrently, or false for serial (default: true)
113 -c, --config [path] path to configuration file, or - to read from stdin
114 --cwd [path] run all tasks in specific directory, instead of the current
115 -d, --debug print additional debug information (default: false)
116 --diff [string] override the default "--staged" flag of "git diff" to get list of files. Implies
117 "--no-stash".
118 --diff-filter [string] override the default "--diff-filter=ACMR" flag of "git diff" to get list of files
119 --max-arg-length [number] maximum length of the command-line argument string (default: 0)
120 --no-stash disable the backup stash, and do not revert in case of errors. Implies
121 "--no-hide-partially-staged".
122 --no-hide-partially-staged disable hiding unstaged changes from partially staged files
123 -q, --quiet disable lint-staged’s own console output (default: false)
124 -r, --relative pass relative filepaths to tasks (default: false)
125 -x, --shell [path] skip parsing of tasks for better shell support (default: false)
126 -v, --verbose show task output even when tasks succeed; by default only failed output is shown
127 (default: false)
128 -h, --help display help for command
129```
130
131- **`--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.
132- **`--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:
133 - `false`: Run all tasks serially
134 - `true` (default) : _Infinite_ concurrency. Runs as many tasks in parallel as possible.
135 - `{number}`: Run the specified number of tasks in parallel, where `1` is equivalent to `false`.
136- **`--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 -`.
137- **`--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.
138- **`--debug`**: Run in debug mode. When set, it does the following:
139 - 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*`.
140 - 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.
141 (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)
142- **`--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`.
143- **`--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).
144- **`--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.
145- **`--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`. This option also implies `--no-hide-partially-staged`.
146- **`--no-hide-partially-staged`**: By default, unstaged changes from partially staged files will be hidden. This option will disable this behavior and include all unstaged changes in partially staged files. Can be re-enabled with `--hide-partially-staged`
147- **`--quiet`**: Supress all CLI output, except from tasks.
148- **`--relative`**: Pass filepaths relative to `process.cwd()` (where `lint-staged` runs) to tasks. Default is `false`.
149- **`--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"`.
150- **`--verbose`**: Show task output even when tasks succeed. By default only failed output is shown.
151
152## Configuration
153
154_Lint-staged_ can be configured in many ways:
155
156- `lint-staged` object in your `package.json`, or [`package.yaml`](https://github.com/pnpm/pnpm/pull/1799)
157- `.lintstagedrc` file in JSON or YML format, or you can be explicit with the file extension:
158 - `.lintstagedrc.json`
159 - `.lintstagedrc.yaml`
160 - `.lintstagedrc.yml`
161- `.lintstagedrc.mjs` or `lint-staged.config.mjs` file in ESM format
162 - the default export value should be a configuration: `export default { ... }`
163- `.lintstagedrc.cjs` or `lint-staged.config.cjs` file in CommonJS format
164 - the exports value should be a configuration: `module.exports = { ... }`
165- `lint-staged.config.js` or `.lintstagedrc.js` in either ESM or CommonJS format, depending on
166 whether your project's _package.json_ contains the `"type": "module"` option or not.
167- Pass a configuration file using the `--config` or `-c` flag
168
169Configuration 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.
170
171You 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.
172
173#### `package.json` example:
174
175```json
176{
177 "lint-staged": {
178 "*": "your-cmd"
179 }
180}
181```
182
183#### `.lintstagedrc` example
184
185```json
186{
187 "*": "your-cmd"
188}
189```
190
191This config will execute `your-cmd` with the list of currently staged files passed as arguments.
192
193So, considering you did `git add file1.ext file2.ext`, lint-staged will run the following command:
194
195`your-cmd file1.ext file2.ext`
196
197### Task concurrency
198
199By 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:
200
201```json
202{
203 "*.ts": "eslint",
204 "*.md": "prettier --list-different"
205}
206```
207
208This 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).
209
210```json
211{
212 "*.ts": ["prettier --list-different", "eslint"],
213 "*.md": "prettier --list-different"
214}
215```
216
217Pay 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_:
218
219```json
220{
221 "*": "prettier --write",
222 "*.ts": "eslint --fix"
223}
224```
225
226You can solve it using the negation pattern and the array syntax:
227
228```json
229{
230 "!(*.ts)": "prettier --write",
231 "*.ts": ["eslint --fix", "prettier --write"]
232}
233```
234
235Another example in which tasks make edits to files and globs match multiple files but don't overlap:
236
237```json
238{
239 "*.css": [
240 "stylelint --fix",
241 "prettier --write"
242 ],
243 "*.{js,jsx}": [
244 "eslint --fix",
245 "prettier --write"
246 ],
247 "!(*.css|*.js|*.jsx)": [
248 "prettier --write"
249 ]
250}
251```
252
253Or, if necessary, you can limit the concurrency using `--concurrent <number>` or disable it entirely with `--concurrent false`.
254
255## Filtering files
256
257Linter 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:
258
259- If the glob pattern contains no slashes (`/`), micromatch's `matchBase` option will be enabled, so globs match a file's basename regardless of directory:
260 - `"*.js"` will match all JS files, like `/test.js` and `/foo/bar/test.js`
261 - `"!(*test).js"` will match all JS files, except those ending in `test.js`, so `foo.js` but not `foo.test.js`
262 - `"!(*.css|*.js)"` will match all files except CSS and JS files
263- If the glob pattern does contain a slash (`/`), it will match for paths as well:
264 - `"./*.js"` will match all JS files in the git repo root, so `/test.js` but not `/foo/bar/test.js`
265 - `"foo/**/*.js"` will match all JS files inside the `/foo` directory, so `/foo/bar/test.js` but not `/test.js`
266
267When matching, lint-staged will do the following
268
269- Resolve the git root automatically, no configuration needed.
270- Pick the staged files which are present inside the project directory.
271- Filter them using the specified glob patterns.
272- Pass absolute paths to the linters as arguments.
273
274**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).
275
276Also see [How to use `lint-staged` in a multi-package monorepo?](#how-to-use-lint-staged-in-a-multi-package-monorepo)
277
278### Ignoring files
279
280The 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.
281
282Consider 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.
283
284In 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).
285
286## What commands are supported?
287
288Supported are any executables installed locally or globally via `npm` as well as any executable from your \$PATH.
289
290> Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn't have it installed.
291
292`lint-staged` uses [execa](https://github.com/sindresorhus/execa#preferlocal) to locate locally installed scripts. So in your `.lintstagedrc` you can write:
293
294```json
295{
296 "*.js": "eslint --fix"
297}
298```
299
300Pass arguments to your commands separated by space as you would do in the shell. See [examples](#examples) below.
301
302## Running multiple commands in a sequence
303
304You 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.
305
306For example:
307
308```json
309{
310 "*.js": ["eslint", "prettier --write"]
311}
312```
313
314going to execute `eslint` and if it exits with `0` code, it will execute `prettier --write` on all staged `*.js` files.
315
316## Using JS configuration files
317
318Writing 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.
319
320If 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.
321
322If 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.
323
324### Function signature
325
326The function can also be async:
327
328```ts
329(filenames: string[]) => string | string[] | Promise<string | string[]>
330```
331
332### Example: Export a function to build your own matchers
333
334<details>
335 <summary>Click to expand</summary>
336
337```js
338// lint-staged.config.js
339import micromatch from 'micromatch'
340
341export default (allStagedFiles) => {
342 const shFiles = micromatch(allStagedFiles, ['**/src/**/*.sh'])
343 if (shFiles.length) {
344 return `printf '%s\n' "Script files aren't allowed in src directory" >&2`
345 }
346 const codeFiles = micromatch(allStagedFiles, ['**/*.js', '**/*.ts'])
347 const docFiles = micromatch(allStagedFiles, ['**/*.md'])
348 return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
349}
350```
351
352</details>
353
354### Example: Wrap filenames in single quotes and run once per file
355
356<details>
357 <summary>Click to expand</summary>
358
359```js
360// .lintstagedrc.js
361export default {
362 '**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`),
363}
364```
365
366</details>
367
368### Example: Run `tsc` on changes to TypeScript files, but do not pass any filename arguments
369
370<details>
371 <summary>Click to expand</summary>
372
373```js
374// lint-staged.config.js
375export default {
376 '**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit',
377}
378```
379
380</details>
381
382### Example: Run ESLint on entire repo if more than 10 staged files
383
384<details>
385 <summary>Click to expand</summary>
386
387```js
388// .lintstagedrc.js
389export default {
390 '**/*.js?(x)': (filenames) =>
391 filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`,
392}
393```
394
395</details>
396
397### Example: Use your own globs
398
399<details>
400 <summary>Click to expand</summary>
401
402It'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.
403
404```js
405// lint-staged.config.js
406import micromatch from 'micromatch'
407
408export default {
409 '*': (allFiles) => {
410 const codeFiles = micromatch(allFiles, ['**/*.js', '**/*.ts'])
411 const docFiles = micromatch(allFiles, ['**/*.md'])
412 return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
413 },
414}
415```
416
417</details>
418
419### Example: Ignore files from match
420
421<details>
422 <summary>Click to expand</summary>
423
424If for some reason you want to ignore files from the glob match, you can use `micromatch.not()`:
425
426```js
427// lint-staged.config.js
428import micromatch from 'micromatch'
429
430export default {
431 '*.js': (files) => {
432 // from `files` filter those _NOT_ matching `*test.js`
433 const match = micromatch.not(files, '*test.js')
434 return `eslint ${match.join(' ')}`
435 },
436}
437```
438
439Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be `!(*test).js`.
440
441</details>
442
443### Example: Use relative paths for commands
444
445<details>
446 <summary>Click to expand</summary>
447
448```js
449import path from 'path'
450
451export default {
452 '*.ts': (absolutePaths) => {
453 const cwd = process.cwd()
454 const relativePaths = absolutePaths.map((file) => path.relative(cwd, file))
455 return `ng lint myProjectName --files ${relativePaths.join(' ')}`
456 },
457}
458```
459
460</details>
461
462## Reformatting the code
463
464Tools 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.
465
466```json
467{
468 "*.js": "prettier --write"
469}
470```
471
472Prior 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.
473
474## Examples
475
476All 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.
477
478```json
479{
480 "name": "My project",
481 "version": "0.1.0",
482 "scripts": {
483 "my-custom-script": "linter --arg1 --arg2"
484 },
485 "lint-staged": {}
486}
487```
488
489In `.husky/pre-commit`
490
491```shell
492#!/usr/bin/env sh
493. "$(dirname "$0")/_/husky.sh"
494
495npx lint-staged
496```
497
498_Note: we don't pass a path as an argument for the runners. This is important since lint-staged will do this for you._
499
500### ESLint with default parameters for `*.js` and `*.jsx` running as a pre-commit hook
501
502<details>
503 <summary>Click to expand</summary>
504
505```json
506{
507 "*.{js,jsx}": "eslint"
508}
509```
510
511</details>
512
513### Automatically fix code style with `--fix` and add to commit
514
515<details>
516 <summary>Click to expand</summary>
517
518```json
519{
520 "*.js": "eslint --fix"
521}
522```
523
524This will run `eslint --fix` and automatically add changes to the commit.
525
526</details>
527
528### Reuse npm script
529
530<details>
531 <summary>Click to expand</summary>
532
533If you wish to reuse a npm script defined in your package.json:
534
535```json
536{
537 "*.js": "npm run my-custom-script --"
538}
539```
540
541The following is equivalent:
542
543```json
544{
545 "*.js": "linter --arg1 --arg2"
546}
547```
548
549</details>
550
551### Use environment variables with linting commands
552
553<details>
554 <summary>Click to expand</summary>
555
556Linting 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).
557
558For example, here is `jest` running on all `.js` files with the `NODE_ENV` variable being set to `"test"`:
559
560```json
561{
562 "*.js": ["cross-env NODE_ENV=test jest --bail --findRelatedTests"]
563}
564```
565
566</details>
567
568### Automatically fix code style with `prettier` for any format Prettier supports
569
570<details>
571 <summary>Click to expand</summary>
572
573```json
574{
575 "*": "prettier --ignore-unknown --write"
576}
577```
578
579</details>
580
581### Automatically fix code style with `prettier` for JavaScript, TypeScript, Markdown, HTML, or CSS
582
583<details>
584 <summary>Click to expand</summary>
585
586```json
587{
588 "*.{js,jsx,ts,tsx,md,html,css}": "prettier --write"
589}
590```
591
592</details>
593
594### Stylelint for CSS with defaults and for SCSS with SCSS syntax
595
596<details>
597 <summary>Click to expand</summary>
598
599```json
600{
601 "*.css": "stylelint",
602 "*.scss": "stylelint --syntax=scss"
603}
604```
605
606</details>
607
608### Run PostCSS sorting and Stylelint to check
609
610<details>
611 <summary>Click to expand</summary>
612
613```json
614{
615 "*.scss": ["postcss --config path/to/your/config --replace", "stylelint"]
616}
617```
618
619</details>
620
621### Minify the images
622
623<details>
624 <summary>Click to expand</summary>
625
626```json
627{
628 "*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged"
629}
630```
631
632<details>
633 <summary>More about <code>imagemin-lint-staged</code></summary>
634
635[imagemin-lint-staged](https://github.com/tomchentw/imagemin-lint-staged) is a CLI tool designed for lint-staged usage with sensible defaults.
636
637See 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.
638
639</details>
640</details>
641
642### Typecheck your staged files with flow
643
644<details>
645 <summary>Click to expand</summary>
646
647```json
648{
649 "*.{js,jsx}": "flow focus-check"
650}
651```
652
653</details>
654
655### Integrate with Next.js
656
657<details>
658 <summary>Click to expand</summary>
659
660```js
661// .lintstagedrc.js
662// See https://nextjs.org/docs/basic-features/eslint#lint-staged for details
663
664const path = require('path')
665
666const buildEslintCommand = (filenames) =>
667 `next lint --fix --file ${filenames.map((f) => path.relative(process.cwd(), f)).join(' --file ')}`
668
669module.exports = {
670 '*.{js,jsx,ts,tsx}': [buildEslintCommand],
671}
672```
673
674</details>
675
676## Frequently Asked Questions
677
678### The output of commit hook looks weird (no colors, duplicate lines, verbose output on Windows, …)
679
680<details>
681 <summary>Click to expand</summary>
682
683Git 2.36.0 introduced a change to hooks where they were no longer run in the original TTY.
684This was fixed in 2.37.0:
685
686https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.37.0.txt
687
688> - In Git 2.36 we revamped the way how hooks are invoked. One change
689> that is end-user visible is that the output of a hook is no longer
690> directly connected to the standard output of "git" that spawns the
691> hook, which was noticed post release. This is getting corrected.
692> (merge [a082345372](https://github.com/git/git/commit/a082345372) ab/hooks-regression-fix later to maint).
693
694If updating Git doesn't help, you can try to manually redirect the output in your Git hook; for example:
695
696```shell
697# .husky/pre-commit
698
699#!/usr/bin/env sh
700. "$(dirname -- "$0")/_/husky.sh"
701
702if sh -c ": >/dev/tty" >/dev/null 2>/dev/null; then exec >/dev/tty 2>&1; fi
703
704npx lint-staged
705```
706
707Source: https://github.com/typicode/husky/issues/968#issuecomment-1176848345
708
709</details>
710
711### Can I use `lint-staged` via node?
712
713<details>
714 <summary>Click to expand</summary>
715
716Yes!
717
718```js
719import lintStaged from 'lint-staged'
720
721try {
722 const success = await lintStaged()
723 console.log(success ? 'Linting was successful!' : 'Linting failed!')
724} catch (e) {
725 // Failed to load configuration
726 console.error(e)
727}
728```
729
730Parameters to `lintStaged` are equivalent to their CLI counterparts:
731
732```js
733const success = await lintStaged({
734 allowEmpty: false,
735 concurrent: true,
736 configPath: './path/to/configuration/file',
737 cwd: process.cwd(),
738 debug: false,
739 maxArgLength: null,
740 quiet: false,
741 relative: false,
742 shell: false,
743 stash: true,
744 verbose: false,
745})
746```
747
748You can also pass config directly with `config` option:
749
750```js
751const success = await lintStaged({
752 allowEmpty: false,
753 concurrent: true,
754 config: { '*.js': 'eslint --fix' },
755 cwd: process.cwd(),
756 debug: false,
757 maxArgLength: null,
758 quiet: false,
759 relative: false,
760 shell: false,
761 stash: true,
762 verbose: false,
763})
764```
765
766The `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.
767
768</details>
769
770### Using with JetBrains IDEs _(WebStorm, PyCharm, IntelliJ IDEA, RubyMine, etc.)_
771
772<details>
773 <summary>Click to expand</summary>
774
775_**Update**_: The latest version of JetBrains IDEs now support running hooks as you would expect.
776
777When 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.
778
779Until the issue is resolved in the IDE, you can use the following config to work around it:
780
781husky v1.x
782
783```json
784{
785 "husky": {
786 "hooks": {
787 "pre-commit": "lint-staged",
788 "post-commit": "git update-index --again"
789 }
790 }
791}
792```
793
794husky v0.x
795
796```json
797{
798 "scripts": {
799 "precommit": "lint-staged",
800 "postcommit": "git update-index --again"
801 }
802}
803```
804
805_Thanks to [this comment](https://youtrack.jetbrains.com/issue/IDEA-135454#comment=27-2710654) for the fix!_
806
807</details>
808
809### How to use `lint-staged` in a multi-package monorepo?
810
811<details>
812 <summary>Click to expand</summary>
813
814Install _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.
815
816For 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/`.
817
818**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:
819
820```js
821// ./.lintstagedrc.json
822{ "*.md": "prettier --write" }
823```
824
825```js
826// ./packages/frontend/.lintstagedrc.json
827{ "*.js": "eslint --fix" }
828```
829
830When 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:
831
832```js
833import baseConfig from '../.lintstagedrc.js'
834
835export default {
836 ...baseConfig,
837 '*.js': 'eslint --fix',
838}
839```
840
841To 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`).
842
843</details>
844
845### Can I lint files outside of the current project folder?
846
847<details>
848 <summary>Click to expand</summary>
849
850tl;dr: Yes, but the pattern should start with `../`.
851
852By default, `lint-staged` executes linters only on the files present inside the project folder(where `lint-staged` is installed and run from).
853So this question is relevant _only_ when the project folder is a child folder inside the git repo.
854In 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.
855
856`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.
857Note that patterns like `*.js`, `**/*.js` will still only match the project files and not any of the files in parent or sibling directories.
858
859Example repo: [sudo-suhas/lint-staged-django-react-demo](https://github.com/sudo-suhas/lint-staged-django-react-demo).
860
861</details>
862
863### Can I run `lint-staged` in CI, or when there are no staged files?
864
865<details>
866 <summary>Click to expand</summary>
867
868Lint-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
869all 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.
870
871Try out the `git diff` command until you are satisfied with the result, for example:
872
873```
874git diff --diff-filter=ACMR --name-only master...my-branch
875```
876
877This will print a list of _added_, _changed_, _modified_, and _renamed_ files between `master` and `my-branch`.
878
879You can then run lint-staged against the same files with:
880
881```
882npx lint-staged --diff="master...my-branch"
883```
884
885</details>
886
887### Can I use `lint-staged` with `ng lint`
888
889<details>
890 <summary>Click to expand</summary>
891
892You 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.
893
894See issue [!951](https://github.com/okonet/lint-staged/issues/951) for more details and possible workarounds.
895
896</details>
897
898### How can I ignore files from `.eslintignore`?
899
900<details>
901 <summary>Click to expand</summary>
902
903ESLint 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 ).
904
905#### ESLint < 7
906
907<details>
908 <summary>Click to expand</summary>
909
910Based 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.
911
912So you can setup a `.lintstagedrc.js` config file to do this:
913
914```js
915import { CLIEngine } from 'eslint'
916
917export default {
918 '*.js': (files) => {
919 const cli = new CLIEngine({})
920 return 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' ')
921 },
922}
923```
924
925</details>
926
927#### ESLint >= 7
928
929<details>
930 <summary>Click to expand</summary>
931
932In 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.
933
934Since [10.5.3](https://github.com/okonet/lint-staged/releases), any errors due to a bad ESLint config will come through to the console.
935
936```js
937import { ESLint } from 'eslint'
938
939const removeIgnoredFiles = async (files) => {
940 const eslint = new ESLint()
941 const isIgnored = await Promise.all(
942 files.map((file) => {
943 return eslint.isPathIgnored(file)
944 })
945 )
946 const filteredFiles = files.filter((_, i) => !isIgnored[i])
947 return filteredFiles.join(' ')
948}
949
950export default {
951 '**/*.{ts,tsx,js,jsx}': async (files) => {
952 const filesToLint = await removeIgnoredFiles(files)
953 return [`eslint --max-warnings=0 ${filesToLint}`]
954 },
955}
956```
957
958</details>
959
960#### ESLint >= 8.51.0 && [Flat ESLint config](https://eslint.org/docs/latest/use/configure/configuration-files-new)
961
962<details>
963 <summary>Click to expand</summary>
964
965ESLint v8.51.0 introduced [`--no-warn-ignored` CLI flag](https://eslint.org/docs/latest/use/command-line-interface#--no-warn-ignored). It suppresses the `warning File ignored because of a matching ignore pattern. Use "--no-ignore" to override` warning, so manually ignoring files via `eslint.isPathIgnored` is no longer necessary.
966
967```json
968{
969 "*.js": "eslint --max-warnings=0 --no-warn-ignored"
970}
971```
972
973**NOTE:** `--no-warn-ignored` flag is only available when [Flat ESLint config](https://eslint.org/docs/latest/use/configure/configuration-files-new) is used.
974
975</details>
976
977</details>