Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork445
🚫💩 — Run tasks like formatters and linters against staged git files
License
lint-staged/lint-staged
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Run tasks like formatters and linters against staged git files and don't let 💩 slip into your code base!
npm install --save-dev lint-staged# requires further setup
$ git commit✔ Backed up original state in git stash (5bda95f)❯ Running tasks for staged files... ❯ packages/frontend/.lintstagedrc.json — 1 file ↓ *.js — no files [SKIPPED] ❯ *.{json,md} — 1 file ⠹ prettier --write ↓ packages/backend/.lintstagedrc.json — 2 files ❯ *.js — 2 files ⠼ eslint --fix ↓ *.{json,md} — no files [SKIPPED]◼ Applying modifications from tasks...◼ Cleaning up temporary files...
- Why
- Installation and setup
- Changelog
- Command line flags
- Configuration
- Filtering files
- What commands are supported?
- Running multiple commands in a sequence
- Using JS configuration files
- Reformatting the code
- Examples
- Frequently Asked Questions
Code quality tasks like formatters and linters make 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 task on a whole project can be slow, and opinionated tasks such as linting can sometimes produce irrelevant results. Ultimately you only want to check files that will be committed.
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.
- Introductory Medium post - Andrey Okonetchnikov, 2016
- Running Jest Tests Before Each Git Commit - Ben McCormick, 2017
- AgentConf presentation - Andrey Okonetchnikov, 2018
- SurviveJS interview - Juho Vepsäläinen and Andrey Okonetchnikov, 2018
- Prettier your CSharp with
dotnet-format
andlint-staged
If you've written one, please submit a PR with the link to it!
To installlint-staged in the recommended way, you need to:
- Installlint-staged itself:
npm install --save-dev lint-staged
- Set up the
pre-commit
git hook to runlint-staged - Install some tools likeESLint orPrettier
- Configurelint-staged to run code checkers and other tasks:
- for example:
{ "*.js": "eslint" }
to run ESLint for all staged JS files - SeeConfiguration for more info
- for example:
Don't forget to commit changes topackage.json
and.husky
to share this setup with your team!
Now change a few files,git add
orgit add --patch
some of them to your commit, and try togit commit
them.
Seeexamples andconfiguration for more information.
Caution
Lint-staged runsgit
operations affecting the files in your repository. By defaultlint-staged creates agit stash
as a backup of the original state before running any configured tasks to help prevent data loss.
SeeReleases.
For breaking changes, seeMIGRATION.md.
❯ npx lint-staged --helpUsage: lint-staged [options]Options: -V, --version output the version number --allow-empty allow empty commits when tasks revert all staged changes (default: false) -p, --concurrent <number|boolean> the number of tasks to run concurrently, or false for serial (default: true) -c, --config [path] path to configuration file, or - to read from stdin --cwd [path] run all tasks in specific directory, instead of the current -d, --debug print additional debug information (default: false) --diff [string] override the default "--staged" flag of "git diff" to get list of files. Implies "--no-stash". --diff-filter [string] override the default "--diff-filter=ACMR" flag of "git diff" to get list of files --max-arg-length [number] maximum length of the command-line argument string (default: 0) --no-revert do not revert to original state in case of errors. --no-stash disable the backup stash. Implies "--no-revert". --no-hide-partially-staged disable hiding unstaged changes from partially staged files -q, --quiet disable lint-staged’s own console output (default: false) -r, --relative pass relative filepaths to tasks (default: false) -v, --verbose show task output even when tasks succeed; by default only failed output is shown (default: false) -h, --help display help for commandAny lost modifications can be restored from a git stash: > git stash list stash@{0}: automatic lint-staged backup > git stash apply --index stash@{0}
--allow-empty
: By default, when 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.--concurrent [number|boolean]
: Controls theconcurrency 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:false
: Run all tasks seriallytrue
(default) :Infinite concurrency. Runs as many tasks in parallel as possible.{number}
: Run the specified number of tasks in parallel, where1
is equivalent tofalse
.
--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 likecat my-config.json | npx lint-staged --config -
.--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.--debug
: Run in debug mode. When set, it does the following:- usesdebug 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
tolint-staged*
. - uses
verbose
renderer forlistr2
; this causes serial, uncoloured output to the terminal, instead of the default (beautified, dynamic) output.(theverbose
renderer can also be activated by setting theTERM=dumb
orNODE_ENV=test
environment variables)
- usesdebug 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
--diff
: By default tasks are filtered against all files staged in git, generated fromgit 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 aboutgit diff andgitrevisions. This option also implies--no-stash
.--diff-filter
: By default only files that areadded,copied,modified, orrenamed are included. Use this flag to override the defaultACMR
value with something else:added (A
),copied (C
),deleted (D
),modified (M
),renamed (R
),type changed (T
),unmerged (U
),unknown (X
), orpairing broken (B
). See also thegit diff
docs for--diff-filter.--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.--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.--no-hide-partially-staged
: By default, unstaged changes from partially staged files will be hidden and applied back after running tasks. This option will disable this behavior, causing those changes to also be committed.--quiet
: Suppress all CLI output, except from tasks.--relative
: Pass filepaths relative toprocess.cwd()
(wherelint-staged
runs) to tasks. Default isfalse
.--no-revert
: By default all task modifications will be reverted in case of an error. This option will disable the behavior, and apply task modifications to the index before aborting the commit.--verbose
: Show task output even when tasks succeed. By default only failed output is shown.
Lint-staged can be configured in many ways:
lint-staged
object in yourpackage.json
, orpackage.yaml
.lintstagedrc
file in JSON or YML format, or you can be explicit with the file extension:.lintstagedrc.json
.lintstagedrc.yaml
.lintstagedrc.yml
.lintstagedrc.mjs
orlint-staged.config.mjs
file in ESM format- the default export value should be a configuration:
export default { ... }
- the default export value should be a configuration:
.lintstagedrc.cjs
orlint-staged.config.cjs
file in CommonJS format- the exports value should be a configuration:
module.exports = { ... }
- the exports value should be a configuration:
lint-staged.config.js
or.lintstagedrc.js
in either ESM or CommonJS format, depending onwhether your project'spackage.json contains the"type": "module"
option or not.- Pass a configuration file using the
--config
or-c
flag
Configuration should be an object where each value is acommand to run and its key is a glob pattern to use for this command. This package usesmicromatch for glob patterns. JavaScript files can also export advanced configuration as a function. SeeUsing JS configuration files for more info.
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 uselint-staged
in a multi-package monorepo?" for more info and an example.
{"lint-staged": {"*":"your-cmd" }}
{"*":"your-cmd"}
This config will executeyour-cmd
with the list of currently staged files passed as arguments.
So, considering you didgit add file1.ext file2.ext
, lint-staged will run the following command:
your-cmd file1.ext file2.ext
Lint-staged provides TypeScript types for the configuration and main Node.js API. You can use the JSDoc syntax in your JS configuration files:
/** *@filename: lint-staged.config.js *@type {import('lint-staged').Configuration} */exportdefault{'*':'prettier --write',}
It's also possible to use the.ts
file extension for the configuration if your Node.js version supports it. The--experimental-strip-types
flag was introduced inNode.js v22.6.0 and unflagged inv23.6.0, enabling Node.js to execute TypeScript files without additional configuration.
export NODE_OPTIONS="--experimental-strip-types"npx lint-staged --config lint-staged.config.ts
By defaultlint-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, botheslint
andprettier
will run at the same time:
{"*.ts":"eslint","*.md":"prettier --list-different"}
This 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 additioneslint
will run for*.ts
filesafter it. Both sets of commands (for each glob) are still started at the same time (but do not overlap).
{"*.ts": ["prettier --list-different","eslint"],"*.md":"prettier --list-different"}
Pay extra attention when the configured globs overlap, and tasks make edits to files. For example, in this configurationprettier
andeslint
might try to make changes to the same*.ts
file at the same time, causing arace condition:
{"*":"prettier --write","*.ts":"eslint --fix"}
You can solve it using the negation pattern and the array syntax:
{"!(*.ts)":"prettier --write","*.ts": ["eslint --fix","prettier --write"]}
Another example in which tasks make edits to files and globs match multiple files but don't overlap:
{"*.css": ["stylelint --fix","prettier --write"],"*.{js,jsx}": ["eslint --fix","prettier --write"],"!(*.css|*.js|*.jsx)": ["prettier --write"]}
Or, if necessary, you can limit the concurrency using--concurrent <number>
or disable it entirely with--concurrent false
.
Task commands work on a subset of all staged files, defined by aglob pattern. lint-staged usesmicromatch for matching files with the following rules:
- If the glob pattern contains no slashes (
/
), micromatch'smatchBase
option will be enabled, so globs match a file's basename regardless of directory:"*.js"
will match all JS files, like/test.js
and/foo/bar/test.js
"!(*test).js"
will match all JS files, except those ending intest.js
, sofoo.js
but notfoo.test.js
"!(*.css|*.js)"
will match all files except CSS and JS files
- If the glob pattern does contain a slash (
/
), it will match for paths as well:"./*.js"
will match all JS files in the git repo root, so/test.js
but not/foo/bar/test.js
"foo/**/*.js"
will match all JS files inside the/foo
directory, so/foo/bar/test.js
but not/test.js
When matching, lint-staged will do the following
- Resolve the git root automatically, no configuration needed.
- Pick the staged files which are present inside the project directory.
- Filter them using the specified glob patterns.
- Pass absolute paths to the tasks as arguments.
NOTE:lint-staged
will passabsolute paths to the tasks 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 yourpackage.json
directory).
Also seeHow to uselint-staged
in a multi-package monorepo?
The concept oflint-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.
Consider a project that usesprettier
to keep code format consistent across all files. The project also stores minified 3rd-party vendor libraries in thevendor/
directory. To keepprettier
from throwing errors on these files, the vendor directory should be added to prettier's ignore configuration, the.prettierignore
file. Runningnpx prettier .
will ignore the entire vendor directory, throwing no errors. Whenlint-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.
In advanced scenarios, where it is impossible to configure the linter task itself to ignore files, but some staged files should still be ignored bylint-staged
, it is possible to filter filepaths before passing them to tasks by using the function syntax. SeeExample: Ignore files from match.
Supported are any executables installed locally or globally vianpm
as well as any executable from your $PATH.
Using globally installed scripts is discouraged, since lint-staged may not work for someone who doesn't have it installed.
lint-staged
usesnano-spawn to locate locally installed scripts. So in your.lintstagedrc
you can write:
{"*.js":"eslint --fix"}
This will result inlint-staged runningeslint --fix file-1.js file-2.js
, when you have staged filesfile-1.js
,file-2.js
andREADME.md
.
Pass arguments to your commands separated by space as you would do in the shell. Seeexamples below.
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 likeeslint --fix
orstylefmt
but can be used for any arbitrary sequences.
For example:
{"*.js": ["eslint","prettier --write"]}
going to executeeslint
and if it exits with0
code, it will executeprettier --write
on all staged*.js
files.
This will result inlint-staged runningeslint file-1.js file-2.js
, when you have staged filesfile-1.js
,file-2.js
andREADME.md
, and if it passes,prettier --write file-1.js file-2.js
.
Writing the configuration file in JavaScript is the most powerful way to configure lint-staged (lint-staged.config.js
,similar, or passed via--config
). From the configuration file, you can export either a single function or an object.
If theexports
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.
If theexports
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.
To summarize, by defaultlint-staged automatically adds the list of matched staged files to your command, but when building the command using JS functions it is expected to do this manually. For example:
exportdefault{'*.js':(stagedFiles)=>[`eslint .`,`prettier --write${stagedFiles.join(' ')}`],}
This will result inlint-staged first runningeslint .
(matchingall files), and if it passes,prettier --write file-1.js file-2.js
, when you have staged filesfile-1.js
,file-2.js
andREADME.md
.
You can also configurelint-staged to run a JavaScript/Node.js script directly, passing the list of staged files as an argument:
exportdefault{'*.js':{title:'Log staged JS files to console',task:async(files)=>{console.log('Staged JS files:',files)},},}
Click to expand
// lint-staged.config.jsimportmicromatchfrom'micromatch'exportdefault(allStagedFiles)=>{constshFiles=micromatch(allStagedFiles,['**/src/**/*.sh'])if(shFiles.length){return`printf '%s\n' "Script files aren't allowed in src directory" >&2`}constcodeFiles=micromatch(allStagedFiles,['**/*.js','**/*.ts'])constdocFiles=micromatch(allStagedFiles,['**/*.md'])return[`eslint${codeFiles.join(' ')}`,`mdl${docFiles.join(' ')}`]}
Click to expand
// .lintstagedrc.jsexportdefault{'**/*.js?(x)':(filenames)=>filenames.map((filename)=>`prettier --write '${filename}'`),}
Click to expand
// lint-staged.config.jsexportdefault{'**/*.ts?(x)':()=>'tsc -p tsconfig.json --noEmit',}
Click to expand
// .lintstagedrc.jsexportdefault{'**/*.js?(x)':(filenames)=>filenames.length>10 ?'eslint .' :`eslint${filenames.join(' ')}`,}
Click to expand
It's better to use thefunction-based configuration (seen above), if your use case is this.
// lint-staged.config.jsimportmicromatchfrom'micromatch'exportdefault{'*':(allFiles)=>{constcodeFiles=micromatch(allFiles,['**/*.js','**/*.ts'])constdocFiles=micromatch(allFiles,['**/*.md'])return[`eslint${codeFiles.join(' ')}`,`mdl${docFiles.join(' ')}`]},}
Click to expand
If for some reason you want to ignore files from the glob match, you can usemicromatch.not()
:
// lint-staged.config.jsimportmicromatchfrom'micromatch'exportdefault{'*.js':(files)=>{// from `files` filter those _NOT_ matching `*test.js`constmatch=micromatch.not(files,'*test.js')return`eslint${match.join(' ')}`},}
Please note that for most cases, globs can achieve the same effect. For the above example, a matching glob would be!(*test).js
.
Click to expand
importpathfrom'path'exportdefault{'*.ts':(absolutePaths)=>{constcwd=process.cwd()constrelativePaths=absolutePaths.map((file)=>path.relative(cwd,file))return`ng lint myProjectName --files${relativePaths.join(' ')}`},}
Tools likePrettier, ESLint/TSLint, or stylelint can reformat your code according to an appropriate config by runningprettier --write
/eslint --fix
/tslint --fix
/stylelint --fix
. Lint-staged will automatically add any modifications to the commit as long as there are no errors.
{"*.js":"prettier --write"}
Prior to version 10, tasks had to manually includegit 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 detectsgit add
in task configurations, it will show a warning in the console. Please removegit add
from your configuration after upgrading.
All examples assume you've already set up lint-staged in thepackage.json
file andhusky in its own config file.
{"name":"My project","version":"0.1.0","scripts": {"my-custom-script":"linter --arg1 --arg2" },"lint-staged": {}}
In.husky/pre-commit
# .husky/pre-commitnpx lint-staged
Note: we don't pass a path as an argument for the runners. This is important since lint-staged will do this for you.
Click to expand
{"*.{js,jsx}":"eslint"}
Click to expand
{"*.js":"eslint --fix"}
This will runeslint --fix
and automatically add changes to the commit.
Click to expand
If you wish to reuse a npm script defined in your package.json:
{"*.js":"npm run my-custom-script --"}
The following is equivalent:
{"*.js":"linter --arg1 --arg2"}
Click to expand
Task commandsdo not support the shell convention of expanding environment variables. To enable the convention yourself, use a tool likecross-env
.
For example, here isjest
running on all.js
files with theNODE_ENV
variable being set to"test"
:
{"*.js": ["cross-env NODE_ENV=test jest --bail --findRelatedTests"]}
Click to expand
{"*":"prettier --ignore-unknown --write"}
Click to expand
{"*.{js,jsx,ts,tsx,md,html,css}":"prettier --write"}
Click to expand
{"*.css":"stylelint","*.scss":"stylelint --syntax=scss"}
Click to expand
{"*.scss": ["postcss --config path/to/your/config --replace","stylelint"]}
Click to expand
{"*.{png,jpeg,jpg,gif,svg}":"imagemin-lint-staged"}
More aboutimagemin-lint-staged
imagemin-lint-staged is a CLI tool designed for lint-staged usage with sensible defaults.
See more onthis blog post for benefits of this approach.
Click to expand
{"*.{js,jsx}":"flow focus-check"}
Click to expand
// .lintstagedrc.js// See https://nextjs.org/docs/basic-features/eslint#lint-staged for detailsconstpath=require('path')constbuildEslintCommand=(filenames)=>`next lint --fix --file${filenames.map((f)=>path.relative(process.cwd(),f)).join(' --file ')}`module.exports={'*.{js,jsx,ts,tsx}':[buildEslintCommand],}
Click to expand
Git 2.36.0 introduced a change to hooks where they were no longer run in the original TTY.This was fixed in 2.37.0:
https://raw.githubusercontent.com/git/git/master/Documentation/RelNotes/2.37.0.txt
- In Git 2.36 we revamped the way how hooks are invoked. One changethat is end-user visible is that the output of a hook is no longerdirectly connected to the standard output of "git" that spawns thehook, which was noticed post release. This is getting corrected.(mergea082345372 ab/hooks-regression-fix later to maint).
If updating Git doesn't help, you can try to manually redirect the output in your Git hook; for example:
# .husky/pre-commitif sh -c": >/dev/tty">/dev/null2>/dev/null;thenexec>/dev/tty2>&1;finpx lint-staged
Source:typicode/husky#968 (comment)
Click to expand
Yes!
importlintStagedfrom'lint-staged'try{constsuccess=awaitlintStaged()console.log(success ?'Linting was successful!' :'Linting failed!')}catch(e){// Failed to load configurationconsole.error(e)}
Parameters tolintStaged
are equivalent to their CLI counterparts:
constsuccess=awaitlintStaged({allowEmpty:false,concurrent:true,configPath:'./path/to/configuration/file',cwd:process.cwd(),debug:false,maxArgLength:null,quiet:false,relative:false,stash:true,verbose:false,})
You can also pass config directly withconfig
option:
constsuccess=awaitlintStaged({allowEmpty:false,concurrent:true,config:{'*.js':'eslint --fix'},cwd:process.cwd(),debug:false,maxArgLength:null,quiet:false,relative:false,stash:true,verbose:false,})
ThemaxArgLength
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.
Click to expand
Update: The latest version of JetBrains IDEs now support running hooks as you would expect.
When using the IDE's GUI to commit changes with theprecommit
hook, you might see inconsistencies in the IDE and command line. This isknown issue at JetBrains so if you want this fixed, please vote for it on YouTrack.
Until the issue is resolved in the IDE, you can use the following config to work around it:
husky v1.x
{"husky": {"hooks": {"pre-commit":"lint-staged","post-commit":"git update-index --again" } }}
husky v0.x
{"scripts": {"precommit":"lint-staged","postcommit":"git update-index --again" }}
Thanks tothis comment for the fix!
Click to expand
Installlint-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 tasks do not "leak" into other packages.
For example, in a monorepo withpackages/frontend/.lintstagedrc.json
andpackages/backend/.lintstagedrc.json
, a staged file insidepackages/frontend/
will only match that configuration, and not the one inpackages/backend/
.
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:
// ./.lintstagedrc.json{"*.md":"prettier --write"}
// ./packages/frontend/.lintstagedrc.json{"*.js":"eslint --fix"}
When committing./packages/frontend/README.md
, itwill not runprettier, because the configuration in thefrontend/
directory is closer to the file and doesn't include it. You should treat alllint-staged configuration files as isolated and separated from each other. You can always use JS files to "extend" configurations, for example:
importbaseConfigfrom'../.lintstagedrc.js'exportdefault{ ...baseConfig,'*.js':'eslint --fix',}
To support backwards-compatibility, monorepo features require multiplelint-staged configuration files present in the git repo. If you still want to runlint-staged in only one of the packages in a monorepo, you can use the--cwd
option (for example,lint-staged --cwd packages/frontend
).
Click to expand
tl;dr: Yes, but the pattern should start with../
.
By default,lint-staged
executes tasks only on the files present inside the project folder(wherelint-staged
is installed and run from).So this question is relevantonly when the project folder is a child folder inside the git repo.In certain project setups, it might be desirable to bypass this restriction. See#425,#487 for more context.
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.Note that patterns like*.js
,**/*.js
will still only match the project files and not any of the files in parent or sibling directories.
Example repo:sudo-suhas/lint-staged-django-react-demo.
Click to expand
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 exampleall changed files between two different branches. If you want to runlint-staged in the CI, maybe you can set it up to compare the branch in aPull Request/Merge Request to the target branch.
Try out thegit diff
command until you are satisfied with the result, for example:
git diff --diff-filter=ACMR --name-only main...my-branch
This will print a list ofadded,changed,modified, andrenamed files betweenmain
andmy-branch
.
You can then run lint-staged against the same files with:
npx lint-staged --diff="main...my-branch"
Click to expand
You should not useng lint
throughlint-staged, because it's designed to lint an entire project. Instead, you can addng lint
to your git pre-commit hook the same way as you would run lint-staged.
See issue!951 for more details and possible workarounds.
Click to expand
ESLint throws outwarning 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 ).
Click to expand
Based on the discussion fromthis issue, it was decided that usingthe outlined scriptis the best route to fix this.
So you can setup a.lintstagedrc.js
config file to do this:
import{CLIEngine}from'eslint'exportdefault{'*.js':(files)=>{constcli=newCLIEngine({})return'eslint --max-warnings=0 '+files.filter((file)=>!cli.isPathIgnored(file)).join(' ')},}
Click to expand
In versions of ESLint > 7,isPathIgnored is an async function and now returns a promise. The code below can be used to reinstate the above functionality.
Since10.5.3, any errors due to a bad ESLint config will come through to the console.
import{ESLint}from'eslint'constremoveIgnoredFiles=async(files)=>{consteslint=newESLint()constisIgnored=awaitPromise.all(files.map((file)=>{returneslint.isPathIgnored(file)}))constfilteredFiles=files.filter((_,i)=>!isIgnored[i])returnfilteredFiles.join(' ')}exportdefault{'**/*.{ts,tsx,js,jsx}':async(files)=>{constfilesToLint=awaitremoveIgnoredFiles(files)return[`eslint --max-warnings=0${filesToLint}`]},}
ESLint >= 8.51.0 &&Flat ESLint config
Click to expand
ESLint v8.51.0 introduced--no-warn-ignored
CLI flag. It suppresses thewarning File ignored because of a matching ignore pattern. Use "--no-ignore" to override
warning, so manually ignoring files viaeslint.isPathIgnored
is no longer necessary.
{"*.js":"eslint --max-warnings=0 --no-warn-ignored"}
NOTE:--no-warn-ignored
flag is only available whenFlat ESLint config is used.
Click to expand
When runninglint-staged
via Husky hooks, TypeScript may ignoretsconfig.json
, leading to errors like:
TS17004: Cannot use JSX unless the '--jsx' flag is provided.TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
See issue#825 for more details.
lint-staged
automatically passes matched staged files as arguments to commands.- Certain input files can cause TypeScript to ignore
tsconfig.json
. For more details, see this TypeScript issue:Allow tsconfig.json when input files are specified.
Workaround: Use afunction signature for thetsc
command
As suggested by @antoinerousseau in#825 (comment), using a function preventslint-staged
from appending file arguments:
Before:
// package.json"lint-staged":{"*.{ts,tsx}":["tsc --noEmit","prettier --write"]}
After:
// lint-staged.config.jsmodule.exports={'*.{ts,tsx}':[()=>'tsc --noEmit','prettier --write'],}
About
🚫💩 — Run tasks like formatters and linters against staged git files
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.