Top Related Projects
🚫💩 — Run linters on git staged files
Git hooks made easy 🐶 woof!
⚡ Get Pretty Quick
A framework for managing and maintaining multi-language pre-commit hooks.
📓 Lint commit messages
Quick Overview
lint-staged is a tool that allows you to run linters and other code quality checks on files that are staged in your Git repository. It helps to ensure that only well-formatted code is committed, improving the overall codebase quality and maintainability.
Pros
- Automated Code Quality Checks: lint-staged automatically runs your configured linters and other code quality tools on the files that are staged for commit, ensuring that only well-formatted code is committed.
- Flexible Configuration: lint-staged allows you to configure which linters and tools to run, and how to run them, making it highly customizable to your project's needs.
- Incremental Checks: lint-staged only runs the checks on the files that have been staged for commit, which can significantly improve the performance of the checks, especially in large codebases.
- Integrates with Git Hooks: lint-staged can be easily integrated with Git hooks, such as the pre-commit hook, to run the checks automatically before each commit.
Cons
- Dependency Management: lint-staged requires you to have the necessary linters and tools installed and configured in your project, which can add complexity to the setup process.
- Potential Slowdown: If your linters and code quality checks are slow, running them on every commit can slow down the development workflow.
- Limited Scope: lint-staged only runs checks on the files that are staged for commit, so it doesn't catch issues in files that haven't been staged.
- Potential Conflicts with Other Git Hooks: If you have other Git hooks set up, there may be potential conflicts or interactions that need to be managed.
Code Examples
Here are a few examples of how to use lint-staged in your project:
- Basic Configuration:
{
"lint-staged": {
"*.js": ["eslint --fix", "git add"]
}
}
This configuration runs the eslint --fix
command on all JavaScript files that are staged for commit, and then adds the fixed files back to the staging area.
- Configuring Multiple Linters:
{
"lint-staged": {
"*.js": ["eslint --fix", "prettier --write", "git add"],
"*.css": ["stylelint --fix", "git add"],
"*.md": ["markdownlint", "git add"]
}
}
This configuration runs eslint --fix
and prettier --write
on JavaScript files, stylelint --fix
on CSS files, and markdownlint
on Markdown files, and then adds the fixed files back to the staging area.
- Ignoring Files:
{
"lint-staged": {
"*.js": ["eslint --fix", "git add"],
"!**/vendor/**": ["prettier --write", "git add"]
}
}
This configuration runs eslint --fix
on all JavaScript files, but excludes any files in the vendor/
directory from the prettier --write
command.
Getting Started
To get started with lint-staged, follow these steps:
- Install the
lint-staged
package as a development dependency in your project:
npm install --save-dev lint-staged
- Create a
.lintstagedrc.json
file in the root of your project and configure the linters and tools you want to run:
{
"*.js": ["eslint --fix", "prettier --write", "git add"],
"*.css": ["stylelint --fix", "git add"],
"*.md": ["markdownlint", "git add"]
}
- Add the following script to your
package.json
file:
{
"scripts": {
"precommit": "lint-staged"
}
}
- Now, whenever you stage files for a commit, lint-staged will automatically run the configured linters and code quality checks on the staged files.
That's it! With these simple steps, you can start using lint-staged to improve the quality of your codebase and ensure that only well-formatted code is committed.
Competitor Comparisons
🚫💩 — Run linters on git staged files
Pros of lint-staged
- Widely adopted and well-maintained project
- Extensive documentation and community support
- Integrates seamlessly with popular linting tools and version control systems
Cons of lint-staged
- May require additional configuration for complex setups
- Can potentially slow down the commit process for large projects
Code Comparison
Both repositories contain the same codebase, as they are the same project. Here's a sample of the core functionality:
const runScripts = async (ctx) => {
const { config, gitDir, files, quiet } = ctx
const normalizedConfig = normalizeConfig(config, gitDir)
const tasks = generateTasks(normalizedConfig, files)
const runner = createRunner(ctx)
return runner(tasks)
}
This code snippet demonstrates the main function responsible for running linting scripts on staged files. It's identical in both repositories, as they are the same project maintained by the lint-staged organization.
Summary
The comparison between lint-staged/lint-staged and lint-staged/lint-staged is not applicable, as they are the same repository. The project is a popular tool for running linters on staged git files, helping developers maintain code quality before committing changes. It offers flexibility in configuration and supports various linting tools, making it a valuable addition to many development workflows.
Git hooks made easy 🐶 woof!
Pros of husky
- Supports a wider range of Git hooks, not limited to pre-commit
- Easier to set up and configure for multiple hooks
- Can run any shell command or script, offering more flexibility
Cons of husky
- May introduce more complexity for simple linting tasks
- Can potentially slow down Git operations if not configured carefully
- Requires separate configuration for each hook type
Code Comparison
husky configuration (.huskyrc.json
):
{
"hooks": {
"pre-commit": "npm test",
"pre-push": "npm run build"
}
}
lint-staged configuration (package.json
):
{
"lint-staged": {
"*.js": ["eslint --fix", "prettier --write"]
}
}
Key Differences
- lint-staged focuses specifically on running commands on staged files, while husky can run commands for various Git hooks
- lint-staged is typically used in conjunction with husky for pre-commit hooks, whereas husky can be used independently
- lint-staged provides built-in optimization for running commands only on changed files, while husky requires additional configuration to achieve this
Use Cases
- Use husky when you need to run commands for multiple Git hooks or execute complex scripts
- Use lint-staged when you primarily want to lint and format staged files before committing
- Consider using both together for a comprehensive Git hooks setup, with lint-staged handling pre-commit linting and husky managing other hooks
⚡ Get Pretty Quick
Pros of Pretty-Quick
- Simpler setup and configuration
- Faster execution for Prettier-only formatting
- Designed specifically for Prettier, optimized for its use case
Cons of Pretty-Quick
- Limited to Prettier formatting only
- Less flexible for complex linting and formatting workflows
- Fewer customization options compared to Lint-Staged
Code Comparison
Lint-Staged configuration:
{
"lint-staged": {
"*.js": ["eslint --fix", "prettier --write"],
"*.css": "stylelint --fix"
}
}
Pretty-Quick usage:
{
"husky": {
"hooks": {
"pre-commit": "pretty-quick --staged"
}
}
}
Summary
Lint-Staged is a more versatile tool that can run various linters and formatters on staged files, offering greater flexibility and customization. It's ideal for projects with complex linting and formatting requirements.
Pretty-Quick, on the other hand, is a simpler and faster option specifically designed for Prettier formatting. It's easier to set up and use but limited to Prettier-only workflows.
Choose Lint-Staged for more comprehensive code quality control and flexibility, or opt for Pretty-Quick if you only need Prettier formatting and prefer a simpler, faster solution.
A framework for managing and maintaining multi-language pre-commit hooks.
Pros of pre-commit
- Language-agnostic, supporting multiple programming languages and tools
- Extensive library of pre-configured hooks for various linters and formatters
- Allows for local and global configuration, providing flexibility for different projects
Cons of pre-commit
- Requires Python installation, which may not be ideal for all projects
- Can be more complex to set up and configure compared to lint-staged
- May have a steeper learning curve for developers unfamiliar with Python ecosystems
Code Comparison
pre-commit configuration (.pre-commit-config.yaml
):
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.1.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
lint-staged configuration (package.json
):
{
"lint-staged": {
"*.js": "eslint --fix",
"*.{js,css,md}": "prettier --write"
}
}
Both tools aim to improve code quality by running checks before committing, but they differ in their approach and ecosystem. pre-commit offers a more versatile, language-agnostic solution with a wide range of pre-configured hooks, while lint-staged provides a simpler, JavaScript-focused setup that integrates well with npm-based projects.
📓 Lint commit messages
Pros of commitlint
- Focuses specifically on enforcing commit message conventions
- Supports custom commit message rules and configurations
- Integrates well with Conventional Commits standard
Cons of commitlint
- Limited to commit message linting, unlike lint-staged's broader scope
- May require additional setup for pre-commit hooks
- Less flexible for running various linting tasks on staged files
Code Comparison
commitlint configuration:
{
"extends": ["@commitlint/config-conventional"],
"rules": {
"type-enum": [2, "always", ["feat", "fix", "docs", "style", "refactor", "test", "chore"]]
}
}
lint-staged configuration:
{
"*.js": ["eslint --fix", "prettier --write"],
"*.css": "stylelint --fix"
}
Key Differences
- Purpose: commitlint focuses on commit message formatting, while lint-staged runs linters on staged files
- Scope: lint-staged is more versatile, allowing various linting tasks on different file types
- Integration: commitlint is often used with husky for commit-msg hooks, while lint-staged is typically used with pre-commit hooks
- Customization: Both offer customization, but lint-staged provides more flexibility for running different tools on staged files
Use Cases
- Use commitlint when enforcing consistent commit messages is a priority
- Choose lint-staged for a more comprehensive pre-commit linting solution across multiple file types and linters
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
ð«ð© lint-staged
Run linters against staged git files and don't let :poop: slip into your code base!
npm install --save-dev lint-staged # requires further setup
$ git commit
â Preparing lint-staged...
⯠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
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.
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.
Related blog posts and talks
- 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!
Installation and setup
To install lint-staged in the recommended way, you need to:
- Install lint-staged itself:
npm install --save-dev lint-staged
- Set up the
pre-commit
git hook to run lint-staged - Install some linters, like ESLint or Prettier
- Configure lint-staged to run linters and other tasks:
- for example:
{ "*.js": "eslint" }
to run ESLint for all staged JS files - See Configuration for more info
- for example:
Don't forget to commit changes to package.json
and .husky
to share this setup with your team!
Now change a few files, git add
or git add --patch
some of them to your commit, and try to git commit
them.
See examples and configuration for more information.
Changelog
See Releases.
Migration
v15
- Since
v15.0.0
lint-staged no longer supports Node.js 16. Please upgrade your Node.js version to at least18.12.0
.
v14
- Since
v14.0.0
lint-staged no longer supports Node.js 14. Please upgrade your Node.js version to at least16.14.0
.
v13
- Since
v13.0.0
lint-staged no longer supports Node.js 12. Please upgrade your Node.js version to at least14.13.1
, or16.0.0
onward. - Version
v13.3.0
was incorrectly released including code of versionv14.0.0
. This means the breaking changes ofv14
are also included inv13.3.0
, the lastv13
version released
v12
- Since
v12.0.0
lint-staged is a pure ESM module, so make sure your Node.js version is at least12.20.0
,14.13.1
, or16.0.0
. Read more about ESM modules from the official Node.js Documentation site here.
v10
- From
v10.0.0
onwards any new modifications to originally staged files will be automatically added to the commit. If your task previously contained agit add
step, please remove this. The automatic behaviour ensures there are less race-conditions, since trying to run multiple git operations at the same time usually results in an error. - From
v10.0.0
onwards, lint-staged uses git stashes to improve speed and provide backups while running. Since git stashes require at least an initial commit, you shouldn't run lint-staged in an empty repo. - From
v10.0.0
onwards, lint-staged requires Node.js version 10.13.0 or later. - 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.
Command line flags
⯠npx lint-staged --help
Usage: 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-stash disable the backup stash, and do not revert in case of errors. Implies
"--no-hide-partially-staged".
--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)
-x, --shell [path] skip parsing of tasks for better shell support (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 command
--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.--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: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:- uses 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
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)
- uses 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
--diff
: By default linters 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 about git diff and gitrevisions. This option also implies--no-stash
.--diff-filter
: By default only files that are added, copied, modified, or renamed 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
), or pairing 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. Can be re-enabled with--stash
. This option also implies--no-hide-partially-staged
.--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
--quiet
: Supress all CLI output, except from tasks.--relative
: Pass filepaths relative toprocess.cwd()
(wherelint-staged
runs) to tasks. Default isfalse
.--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"
.--verbose
: Show task output even when tasks succeed. By default only failed output is shown.
Configuration
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 on whether your project's package.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 a command to run and its key is a glob pattern to use for this command. This package uses micromatch for glob patterns. JavaScript files can also export advanced configuration as a function. See Using 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 use lint-staged
in a multi-package monorepo?" for more info and an example.
package.json
example:
{
"lint-staged": {
"*": "your-cmd"
}
}
.lintstagedrc
example
{
"*": "your-cmd"
}
This config will execute your-cmd
with the list of currently staged files passed as arguments.
So, considering you did git add file1.ext file2.ext
, lint-staged will run the following command:
your-cmd file1.ext file2.ext
Task concurrency
By 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:
{
"*.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 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).
{
"*.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 configuration prettier
and eslint
might try to make changes to the same *.ts
file at the same time, causing a race 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
.
Filtering files
Linter commands work on a subset of all staged files, defined by a glob pattern. lint-staged uses micromatch 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 linters as arguments.
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).
Also see How to use lint-staged
in a multi-package monorepo?
Ignoring files
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.
Consider a project that uses prettier
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.
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.
What commands are supported?
Supported are any executables installed locally or globally via npm
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
uses execa to locate locally installed scripts. So in your .lintstagedrc
you can write:
{
"*.js": "eslint --fix"
}
This will result in lint-staged running eslint --fix file-1.js file-2.js
, when you have staged files file-1.js
, file-2.js
and README.md
.
Pass arguments to your commands separated by space as you would do in the shell. See examples below.
Running multiple commands in a sequence
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.
For example:
{
"*.js": ["eslint", "prettier --write"]
}
going to execute eslint
and if it exits with 0
code, it will execute prettier --write
on all staged *.js
files.
This will result in lint-staged running eslint file-1.js file-2.js
, when you have staged files file-1.js
, file-2.js
and README.md
, and if it passes, prettier --write file-1.js file-2.js
.
Using JS configuration files
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 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.
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.
To summarize, by default lint-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:
export default {
'*.js': (stagedFiles) => [`eslint .`, `prettier --write ${stagedFiles.join(' ')}`],
}
This will result in lint-staged first running eslint .
(matching all files), and if it passes, prettier --write file-1.js file-2.js
, when you have staged files file-1.js
, file-2.js
and README.md
.
Function signature
The function can also be async:
(filenames: string[]) => string | string[] | Promise<string | string[]>
Example: Export a function to build your own matchers
Click to expand
// lint-staged.config.js
import micromatch from 'micromatch'
export default (allStagedFiles) => {
const shFiles = micromatch(allStagedFiles, ['**/src/**/*.sh'])
if (shFiles.length) {
return `printf '%s\n' "Script files aren't allowed in src directory" >&2`
}
const codeFiles = micromatch(allStagedFiles, ['**/*.js', '**/*.ts'])
const docFiles = micromatch(allStagedFiles, ['**/*.md'])
return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
}
Example: Wrap filenames in single quotes and run once per file
Click to expand
// .lintstagedrc.js
export default {
'**/*.js?(x)': (filenames) => filenames.map((filename) => `prettier --write '${filename}'`),
}
Example: Run tsc
on changes to TypeScript files, but do not pass any filename arguments
Click to expand
// lint-staged.config.js
export default {
'**/*.ts?(x)': () => 'tsc -p tsconfig.json --noEmit',
}
Example: Run ESLint on entire repo if more than 10 staged files
Click to expand
// .lintstagedrc.js
export default {
'**/*.js?(x)': (filenames) =>
filenames.length > 10 ? 'eslint .' : `eslint ${filenames.join(' ')}`,
}
Example: Use your own globs
Click to expand
It's better to use the function-based configuration (seen above), if your use case is this.
// lint-staged.config.js
import micromatch from 'micromatch'
export default {
'*': (allFiles) => {
const codeFiles = micromatch(allFiles, ['**/*.js', '**/*.ts'])
const docFiles = micromatch(allFiles, ['**/*.md'])
return [`eslint ${codeFiles.join(' ')}`, `mdl ${docFiles.join(' ')}`]
},
}
Example: Ignore files from match
Click to expand
If for some reason you want to ignore files from the glob match, you can use micromatch.not()
:
// lint-staged.config.js
import micromatch from 'micromatch'
export default {
'*.js': (files) => {
// from `files` filter those _NOT_ matching `*test.js`
const match = 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
.
Example: Use relative paths for commands
Click to expand
import path from 'path'
export default {
'*.ts': (absolutePaths) => {
const cwd = process.cwd()
const relativePaths = absolutePaths.map((file) => path.relative(cwd, file))
return `ng lint myProjectName --files ${relativePaths.join(' ')}`
},
}
Reformatting the code
Tools like Prettier, 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.
{
"*.js": "prettier --write"
}
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.
Examples
All examples assume you've already set up lint-staged in the package.json
file and husky 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-commit
npx 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.
ESLint with default parameters for *.js
and *.jsx
running as a pre-commit hook
Click to expand
{
"*.{js,jsx}": "eslint"
}
Automatically fix code style with --fix
and add to commit
Click to expand
{
"*.js": "eslint --fix"
}
This will run eslint --fix
and automatically add changes to the commit.
Reuse npm script
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"
}
Use environment variables with linting commands
Click to expand
Linting commands do not support the shell convention of expanding environment variables. To enable the convention yourself, use a tool like cross-env
.
For example, here is jest
running on all .js
files with the NODE_ENV
variable being set to "test"
:
{
"*.js": ["cross-env NODE_ENV=test jest --bail --findRelatedTests"]
}
Automatically fix code style with prettier
for any format Prettier supports
Click to expand
{
"*": "prettier --ignore-unknown --write"
}
Automatically fix code style with prettier
for JavaScript, TypeScript, Markdown, HTML, or CSS
Click to expand
{
"*.{js,jsx,ts,tsx,md,html,css}": "prettier --write"
}
Stylelint for CSS with defaults and for SCSS with SCSS syntax
Click to expand
{
"*.css": "stylelint",
"*.scss": "stylelint --syntax=scss"
}
Run PostCSS sorting and Stylelint to check
Click to expand
{
"*.scss": ["postcss --config path/to/your/config --replace", "stylelint"]
}
Minify the images
Click to expand
{
"*.{png,jpeg,jpg,gif,svg}": "imagemin-lint-staged"
}
More about imagemin-lint-staged
imagemin-lint-staged is a CLI tool designed for lint-staged usage with sensible defaults.
See more on this blog post for benefits of this approach.
Typecheck your staged files with flow
Click to expand
{
"*.{js,jsx}": "flow focus-check"
}
Integrate with Next.js
Click to expand
// .lintstagedrc.js
// See https://nextjs.org/docs/basic-features/eslint#lint-staged for details
const path = require('path')
const buildEslintCommand = (filenames) =>
`next lint --fix --file ${filenames.map((f) => path.relative(process.cwd(), f)).join(' --file ')}`
module.exports = {
'*.{js,jsx,ts,tsx}': [buildEslintCommand],
}
Frequently Asked Questions
The output of commit hook looks weird (no colors, duplicate lines, verbose output on Windows, â¦)
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 change that is end-user visible is that the output of a hook is no longer directly connected to the standard output of "git" that spawns the hook, which was noticed post release. This is getting corrected. (merge a082345372 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-commit
if sh -c ": >/dev/tty" >/dev/null 2>/dev/null; then exec >/dev/tty 2>&1; fi
npx lint-staged
Source: https://github.com/typicode/husky/issues/968#issuecomment-1176848345
Can I use lint-staged
via node?
Click to expand
Yes!
import lintStaged from 'lint-staged'
try {
const success = await lintStaged()
console.log(success ? 'Linting was successful!' : 'Linting failed!')
} catch (e) {
// Failed to load configuration
console.error(e)
}
Parameters to lintStaged
are equivalent to their CLI counterparts:
const success = await lintStaged({
allowEmpty: false,
concurrent: true,
configPath: './path/to/configuration/file',
cwd: process.cwd(),
debug: false,
maxArgLength: null,
quiet: false,
relative: false,
shell: false,
stash: true,
verbose: false,
})
You can also pass config directly with config
option:
const success = await lintStaged({
allowEmpty: false,
concurrent: true,
config: { '*.js': 'eslint --fix' },
cwd: process.cwd(),
debug: false,
maxArgLength: null,
quiet: false,
relative: false,
shell: false,
stash: true,
verbose: false,
})
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.
Using with JetBrains IDEs (WebStorm, PyCharm, IntelliJ IDEA, RubyMine, etc.)
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 the precommit
hook, you might see inconsistencies in the IDE and command line. This is known 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 to this comment for the fix!
How to use lint-staged
in a multi-package monorepo?
Click to expand
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.
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/
.
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
, 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:
import baseConfig from '../.lintstagedrc.js'
export default {
...baseConfig,
'*.js': 'eslint --fix',
}
To 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
).
Can I lint files outside of the current project folder?
Click to expand
tl;dr: Yes, but the pattern should start with ../
.
By default, lint-staged
executes linters only on the files present inside the project folder(where lint-staged
is installed and run from).
So this question is relevant only 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.
Can I run lint-staged
in CI, or when there are no staged files?
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 example 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.
Try out the git diff
command until you are satisfied with the result, for example:
git diff --diff-filter=ACMR --name-only master...my-branch
This will print a list of added, changed, modified, and renamed files between master
and my-branch
.
You can then run lint-staged against the same files with:
npx lint-staged --diff="master...my-branch"
Can I use lint-staged
with ng lint
Click to expand
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.
See issue !951 for more details and possible workarounds.
How can I ignore files from .eslintignore
?
Click to expand
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 ).
ESLint < 7
Click to expand
Based on the discussion from this issue, it was decided that using the outlined scriptis the best route to fix this.
So you can setup a .lintstagedrc.js
config file to do this:
import { CLIEngine } from 'eslint'
export default {
'*.js': (files) => {
const cli = new CLIEngine({})
return 'eslint --max-warnings=0 ' + files.filter((file) => !cli.isPathIgnored(file)).join(' ')
},
}
ESLint >= 7
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.
Since 10.5.3, any errors due to a bad ESLint config will come through to the console.
import { ESLint } from 'eslint'
const removeIgnoredFiles = async (files) => {
const eslint = new ESLint()
const isIgnored = await Promise.all(
files.map((file) => {
return eslint.isPathIgnored(file)
})
)
const filteredFiles = files.filter((_, i) => !isIgnored[i])
return filteredFiles.join(' ')
}
export default {
'**/*.{ts,tsx,js,jsx}': async (files) => {
const filesToLint = await removeIgnoredFiles(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 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.
{
"*.js": "eslint --max-warnings=0 --no-warn-ignored"
}
NOTE: --no-warn-ignored
flag is only available when Flat ESLint config is used.
Top Related Projects
🚫💩 — Run linters on git staged files
Git hooks made easy 🐶 woof!
⚡ Get Pretty Quick
A framework for managing and maintaining multi-language pre-commit hooks.
📓 Lint commit messages
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot