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