UNPKG

22 kBMarkdownView Raw
1# 🚫💩 lint-staged ![GitHub Actions](https://github.com/okonet/lint-staged/workflows/CI/badge.svg) [![Build Status for Windows](https://ci.appveyor.com/api/projects/status/github/okonet/lint-staged?branch=master&svg=true)](https://ci.appveyor.com/project/okonet/lint-staged) [![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[![asciicast](https://asciinema.org/a/199934.svg)](https://asciinema.org/a/199934)
6
7## Why
8
9Linting 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.
10
11This 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.
12
13## Related blogs posts and talks
14
15- [Make Linting Great Again](https://medium.com/@okonetchnikov/make-linting-great-again-f3890e1ad6b8#.8qepn2b5l)
16- [Running Jest Tests Before Each Git Commit](https://benmccormick.org/2017/02/26/running-jest-tests-before-each-git-commit/)
17- [AgentConf: Make Linting Great Again](https://www.youtube.com/watch?v=-mhY7e-EsC4)
18- [SurviveJS Interview](https://survivejs.com/blog/lint-staged-interview/)
19
20> If you've written one, please submit a PR with the link to it!
21
22## Installation and setup
23
24The fastest way to start using lint-staged is to run following command in your terminal:
25
26```bash
27npx mrm lint-staged
28```
29
30It will install and configure [husky](https://github.com/typicode/husky) and lint-staged depending on code quality tools from `package.json` dependencies so please make sure you install (`npm install --save-dev`) and configure all code quality tools like [Prettier](https://prettier.io), [ESlint](https://eslint.org) prior that.
31
32Don't forget to commit changes to `package.json` to share this setup with your team!
33
34Now change a few files, `git add` or `git add --patch` some of them to your commit and try to `git commit` them.
35
36See [examples](#examples) and [configuration](#configuration) for more information.
37
38## Changelog
39
40See [Releases](https://github.com/okonet/lint-staged/releases)
41
42### Migration
43
44#### v10
45
46- From `v10.0.0` onwards any new modifications to originally staged files will be automatically added to the commit.
47 If your task previously contained a `git add` step, please remove this.
48 The automatic behaviour ensures there are less race-conditions,
49 since trying to run multiple git operations at the same time usually results in an error.
50- From `v10.0.0` onwards _lint-staged_ uses git stashes to improve speed and provide backups while running.
51 Since git stashes require at least an initial commit, you shouldn't run _lint-staged_ in an empty repo.
52- From `v10.0.0` onwards _lint-staged_ requires Node.js version 10.13.0 or later.
53- From `v10.0.0` onwards _lint-staged_ will abort the commit if linter tasks undo all staged changes. To allow creating empty commit, please use the `--allow-empty` option.
54
55## Command line flags
56
57```bash
58❯ npx lint-staged --help
59Usage: lint-staged [options]
60
61Options:
62 -V, --version output the version number
63 --allow-empty allow empty commits when tasks revert all staged changes
64 (default: false)
65 -c, --config [path] path to configuration file
66 -d, --debug print additional debug information (default: false)
67 --no-stash disable the backup stash, and do not revert in case of
68 errors
69 -p, --concurrent <parallel tasks> the number of tasks to run concurrently, or false to run
70 tasks serially (default: true)
71 -q, --quiet disable lint-staged’s own console output (default: false)
72 -r, --relative pass relative filepaths to tasks (default: false)
73 -x, --shell skip parsing of tasks for better shell support (default:
74 false)
75 -v, --verbose show task output even when tasks succeed; by default only
76 failed output is shown (default: false)
77 -h, --help display help for command
78```
79
80- **`--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.
81- **`--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 print an error if the specified file cannot be found.
82- **`--debug`**: Run in debug mode. When set, it does the following:
83 - 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*`.
84 - 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.
85- **`--concurrent [number | (true/false)]`**: Controls the concurrency of tasks being run by lint-staged. **NOTE**: This does NOT affect the concurrency of subtasks (they will always be run sequentially). Possible values are:
86 - `false`: Run all tasks serially
87 - `true` (default) : _Infinite_ concurrency. Runs as many tasks in parallel as possible.
88 - `{number}`: Run the specified number of tasks in parallel, where `1` is equivalent to `false`.
89- **`--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.
90- **`--quiet`**: Supress all CLI output, except from tasks.
91- **`--relative`**: Pass filepaths relative to `process.cwd()` (where `lint-staged` runs) to tasks. Default is `false`.
92- **`--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.
93- **`--verbose`**: Show task output even when tasks succeed. By default only failed output is shown.
94
95## Configuration
96
97Starting with v3.1 you can now use different ways of configuring it:
98
99- `lint-staged` object in your `package.json`
100- `.lintstagedrc` file in JSON or YML format
101- `lint-staged.config.js` file in JS format
102- Pass a configuration file using the `--config` or `-c` flag
103
104See [cosmiconfig](https://github.com/davidtheclark/cosmiconfig) for more details on what formats are supported.
105
106Configuration 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.
107
108#### `package.json` example:
109
110```json
111{
112 "lint-staged": {
113 "*": "your-cmd"
114 }
115}
116```
117
118#### `.lintstagedrc` example
119
120```json
121{
122 "*": "your-cmd"
123}
124```
125
126This config will execute `your-cmd` with the list of currently staged files passed as arguments.
127
128So, considering you did `git add file1.ext file2.ext`, lint-staged will run the following command:
129
130`your-cmd file1.ext file2.ext`
131
132## Filtering files
133
134Linter 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:
135
136- If the glob pattern contains no slashes (`/`), micromatch's `matchBase` option will enabled, so globs match a file's basename regardless of directory:
137 - **`"*.js"`** will match all JS files, like `/test.js` and `/foo/bar/test.js`
138 - **`"!(*test).js"`**. will match all JS files, except those ending in `test.js`, so `foo.js` but not `foo.test.js`
139- If the glob pattern does contain a slash (`/`), it will match for paths as well:
140 - **`"./*.js"`** will match all JS files in the git repo root, so `/test.js` but not `/foo/bar/test.js`
141 - **`"foo/**/\*.js"`** will match all JS files inside the`/foo`directory, so`/foo/bar/test.js`but not`/test.js`
142
143When matching, `lint-staged` will do the following
144
145- Resolve the git root automatically, no configuration needed.
146- Pick the staged files which are present inside the project directory.
147- Filter them using the specified glob patterns.
148- Pass absolute paths to the linters as arguments.
149
150**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).
151
152Also see [How to use `lint-staged` in a multi package monorepo?](#how-to-use-lint-staged-in-a-multi-package-monorepo)
153
154### Ignoring files
155
156The concept of `lint-staged` is to run configured linter (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.
157
158Consider 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.
159
160In 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).
161
162## What commands are supported?
163
164Supported are any executables installed locally or globally via `npm` as well as any executable from your \$PATH.
165
166> Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn’t have it installed.
167
168`lint-staged` uses [execa](https://github.com/sindresorhus/execa#preferlocal) to locate locally installed scripts. So in your `.lintstagedrc` you can write:
169
170```json
171{
172 "*.js": "eslint --fix"
173}
174```
175
176Pass arguments to your commands separated by space as you would do in the shell. See [examples](#examples) below.
177
178## Running multiple commands in a sequence
179
180You 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.
181
182For example:
183
184```json
185{
186 "*.js": ["eslint", "prettier --write"]
187}
188```
189
190going to execute `eslint` and if it exits with `0` code, it will execute `prettier --write` on all staged `*.js` files.
191
192## Using JS functions to customize tasks
193
194When supplying configuration in JS format it is possible to define the task as a function, which will receive an array of staged filenames/paths and should return the complete command as a string. It is also possible to return an array of complete command strings, for example when the task supports only a single file input. The function can be either sync or async.
195
196```ts
197type TaskFn = (filenames: string[]) => string | string[] | Promise<string | string[]>
198```
199
200### Example: Wrap filenames in single quotes and run once per file
201
202```js
203// .lintstagedrc.js
204module.exports = {
205 '**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`)
206}
207```
208
209### Example: Run `tsc` on changes to TypeScript files, but do not pass any filename arguments
210
211```js
212// lint-staged.config.js
213module.exports = {
214 '**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit'
215}
216```
217
218### Example: Run eslint on entire repo if more than 10 staged files
219
220```js
221// .lintstagedrc.js
222module.exports = {
223 '**/*.js?(x)': (filenames) =>
224 filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`
225}
226```
227
228### Example: Use your own globs
229
230```js
231// lint-staged.config.js
232const micromatch = require('micromatch')
233
234module.exports = {
235 '*': (allFiles) => {
236 const match = micromatch(allFiles, ['*.js', '*.ts'])
237 return `eslint ${match.join(' ')}`
238 }
239}
240```
241
242### Example: Ignore files from match
243
244If for some reason you want to ignore files from the glob match, you can use `micromatch.not()`:
245
246```js
247// lint-staged.config.js
248const micromatch = require('micromatch')
249
250module.exports = {
251 '*.js': (files) => {
252 // from `files` filter those _NOT_ matching `*test.js`
253 const match = micromatch.not(files, '*test.js')
254 return `eslint ${match.join(' ')}`
255 }
256}
257```
258
259Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be `!(*test).js`.
260
261### Example: Use relative paths for commands
262
263```js
264const path = require('path')
265
266module.exports = {
267 '*.ts': (absolutePaths) => {
268 const cwd = process.cwd()
269 const relativePaths = absolutePaths.map((file) => path.relative(cwd, file))
270 return `ng lint myProjectName --files ${relativePaths.join(' ')}`
271 }
272}
273```
274
275## Reformatting the code
276
277Tools 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.
278
279```json
280{
281 "*.js": "prettier --write"
282}
283```
284
285Prior 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.
286
287## Examples
288
289All examples assuming you’ve already set up lint-staged and husky in the `package.json`.
290
291```json
292{
293 "name": "My project",
294 "version": "0.1.0",
295 "scripts": {
296 "my-custom-script": "linter --arg1 --arg2"
297 },
298 "husky": {
299 "hooks": {
300 "pre-commit": "lint-staged"
301 }
302 },
303 "lint-staged": {}
304}
305```
306
307_Note we don’t pass a path as an argument for the runners. This is important since lint-staged will do this for you._
308
309### ESLint with default parameters for `*.js` and `*.jsx` running as a pre-commit hook
310
311```json
312{
313 "*.{js,jsx}": "eslint"
314}
315```
316
317### Automatically fix code style with `--fix` and add to commit
318
319```json
320{
321 "*.js": "eslint --fix"
322}
323```
324
325This will run `eslint --fix` and automatically add changes to the commit.
326
327### Reuse npm script
328
329If you wish to reuse a npm script defined in your package.json:
330
331```json
332{
333 "*.js": "npm run my-custom-script --"
334}
335```
336
337The following is equivalent:
338
339```json
340{
341 "*.js": "linter --arg1 --arg2"
342}
343```
344
345### Use environment variables with linting commands
346
347Linting 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).
348
349For example, here is `jest` running on all `.js` files with the `NODE_ENV` variable being set to `"test"`:
350
351```json
352{
353 "*.js": ["cross-env NODE_ENV=test jest --bail --findRelatedTests"]
354}
355```
356
357### Automatically fix code style with `prettier` for javascript, typescript, markdown, HTML, or CSS
358
359```json
360{
361 "*.{js,jsx,ts,tsx,md,html,css}": "prettier --write"
362}
363```
364
365### Stylelint for CSS with defaults and for SCSS with SCSS syntax
366
367```json
368{
369 "*.css": "stylelint",
370 "*.scss": "stylelint --syntax=scss"
371}
372```
373
374### Run PostCSS sorting and Stylelint to check
375
376```json
377{
378 "*.scss": ["postcss --config path/to/your/config --replace", "stylelint"]
379}
380```
381
382### Minify the images
383
384```json
385{
386 "*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged"
387}
388```
389
390<details>
391 <summary>More about <code>imagemin-lint-staged</code></summary>
392
393[imagemin-lint-staged](https://github.com/tomchentw/imagemin-lint-staged) is a CLI tool designed for lint-staged usage with sensible defaults.
394
395See 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.
396
397</details>
398
399### Typecheck your staged files with flow
400
401```json
402{
403 "*.{js,jsx}": "flow focus-check"
404}
405```
406
407## Frequently Asked Questions
408
409### Can I use `lint-staged` via node?
410
411Yes!
412
413```js
414const lintStaged = require('lint-staged')
415
416try {
417 const success = await lintStaged()
418 console.log(success ? 'Linting was successful!' : 'Linting failed!')
419} catch (e) {
420 // Failed to load configuration
421 console.error(e)
422}
423```
424
425Parameters to `lintStaged` are equivalent to their CLI counterparts:
426
427```js
428const success = await lintStaged({
429 allowEmpty: false,
430 concurrent: true,
431 configPath: './path/to/configuration/file',
432 cwd: process.cwd(),
433 debug: false,
434 maxArgLength: null,
435 quiet: false,
436 relative: false,
437 shell: false
438 stash: true,
439 verbose: false
440})
441```
442
443You can also pass config directly with `config` option:
444
445```js
446const success = await lintStaged({
447 allowEmpty: false,
448 concurrent: true,
449 config: { '*.js': 'eslint --fix' },
450 cwd: process.cwd(),
451 debug: false,
452 maxArgLength: null,
453 quiet: false,
454 relative: false,
455 shell: false,
456 stash: true,
457 verbose: false
458})
459```
460
461The `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.
462
463### Using with JetBrains IDEs _(WebStorm, PyCharm, IntelliJ IDEA, RubyMine, etc.)_
464
465_**Update**_: The latest version of JetBrains IDEs now support running hooks as you would expect.
466
467When 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.
468
469Until the issue is resolved in the IDE, you can use the following config to work around it:
470
471husky v1.x
472
473```json
474{
475 "husky": {
476 "hooks": {
477 "pre-commit": "lint-staged",
478 "post-commit": "git update-index --again"
479 }
480 }
481}
482```
483
484husky v0.x
485
486```json
487{
488 "scripts": {
489 "precommit": "lint-staged",
490 "postcommit": "git update-index --again"
491 }
492}
493```
494
495_Thanks to [this comment](https://youtrack.jetbrains.com/issue/IDEA-135454#comment=27-2710654) for the fix!_
496
497### How to use `lint-staged` in a multi package monorepo?
498
499Starting with v5.0, `lint-staged` automatically resolves the git root **without any** additional configuration. You configure `lint-staged` as you normally would if your project root and git root were the same directory.
500
501If you wish to use `lint-staged` in a multi package monorepo, it is recommended to install [`husky`](https://github.com/typicode/husky) in the root package.json.
502[`lerna`](https://github.com/lerna/lerna) can be used to execute the `precommit` script in all sub-packages.
503
504Example repo: [sudo-suhas/lint-staged-multi-pkg](https://github.com/sudo-suhas/lint-staged-multi-pkg).
505
506### Can I lint files outside of the current project folder?
507
508tl;dr: Yes, but the pattern should start with `../`.
509
510By default, `lint-staged` executes linters only on the files present inside the project folder(where `lint-staged` is installed and run from).
511So this question is relevant _only_ when the project folder is a child folder inside the git repo.
512In 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.
513
514`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.
515Note that patterns like `*.js`, `**/*.js` will still only match the project files and not any of the files in parent or sibling directories.
516
517Example repo: [sudo-suhas/lint-staged-django-react-demo](https://github.com/sudo-suhas/lint-staged-django-react-demo).
518
519### How can i ignore files from `.eslintignore` ?
520
521ESLint 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 ).
522
523Based on the discussion from 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.
524
525So you can setup a `.lintstagedrc.js` config file to do this:
526
527```js
528const { CLIEngine } = require('eslint')
529
530const cli = new CLIEngine({})
531
532module.exports = {
533 '*.js': (files) =>
534 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' ')
535}
536```