Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
lint-staged
Advanced tools
The lint-staged npm package is used to run linters on staged git files. It allows you to run specific commands before committing, ensuring that only clean, linted code gets committed to your repository. This helps in maintaining code quality and reducing the chances of committing code with errors or that doesn't adhere to the project's coding standards.
Running linters on staged files
This configuration in package.json will run ESLint on staged JavaScript files and Stylelint on staged CSS files, automatically fixing any fixable issues.
"lint-staged": {
"*.js": "eslint --fix",
"*.css": "stylelint --fix"
}
Running custom scripts
This configuration will run markdownlint-cli2 on staged Markdown files to ensure they meet the project's markdown style requirements.
"lint-staged": {
"*.md": "npx markdownlint-cli2"
}
Using with pre-commit hooks
This configuration sets up Husky to run lint-staged as a pre-commit hook, ensuring that the linters are run automatically before each commit.
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
pretty-quick is an npm package that runs Prettier on your changed files. It is similar to lint-staged but is specifically focused on formatting with Prettier rather than running arbitrary linters or tasks.
Husky can be used to manage Git hooks and can run tasks on commit, push, and more. While it doesn't run linters on staged files by itself, it is often used in conjunction with lint-staged to trigger linters before a commit.
Lefthook is a fast and powerful Git hooks manager for Node.js, Ruby, or any other type of projects. It can run linters and custom scripts similar to lint-staged, but it also provides additional features like parallel task execution and support for multiple programming languages.
Run linters against staged git files and don't let :poop: slip into your code base!
The latest versions of lint-staged
require Node.js v6 or newer. (Versions of lint-staged
prior to v7 still work with Node.js v4.)
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.
If you've written one, please submit a PR with the link to it!
A fast way to perform the below is to run
npx mrm lint-staged
. It does most of the setup for you.
npm install --save-dev lint-staged husky
.eslintrc
, .stylelintrc
, etc.package.json
like this:{
"scripts": {
+ "precommit": "lint-staged"
},
+ "lint-staged": {
+ "*.js": ["eslint --fix", "git add"]
+ }
}
Now change a few files, git add
some of them to your commit and try to git commit
them.
This is how it looks in action:
See examples and configuration below.
I recommend using husky to manage git hooks but you can use any other tool.
NOTE:
If you're using commitizen and having following npm-script
{ commit: git-cz }
,precommit
hook will run twice before commitizen cli and after the commit. This buggy behaviour is introduced by husky.To mitigate this rename your
commit
npm script to something non git hook namespace like, for example{ cz: git-cz }
$ ./node_modules/.bin/lint-staged --help
Usage: lint-staged [options]
Options:
-V, --version output the version number
-c, --config [path] Configuration file path or package
-d, --debug Enable debug mode
-h, --help output usage information
--config [path]
: This can be used to manually specify the lint-staged
config file location. However, if the specified file cannot be found, it will error out instead of performing the usual search. You may pass a npm package name for configuration also.--debug
: Enabling the debug mode does the following:
lint-staged
uses the debug module internally to log 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*
.verbose
renderer for listr
.--silent
to npm scripts.Starting with v3.1 you can now use different ways of configuring it:
lint-staged
object in your package.json
.lintstagedrc
file in JSON or YML formatlint-staged.config.js
file in JS format--config
or -c
flagSee cosmiconfig for more details on what formats are supported.
Lint-staged supports simple and advanced config formats.
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.
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
To extend and customise lint-staged, advanced options are available. To use these options the format should be as the following:
package.json
example with ignore
option:{
"lint-staged": {
"linters": {
"*.{js,scss}": ["some command", "git add"]
},
"ignore": ["**/dist/*.min.js"]
}
}
Notice that the linting commands now are nested into the linters
object. The following options are available for advance configuration:
concurrent
— true — runs linters for each glob pattern simultaneously. If you don’t want this, you can set concurrent: false
chunkSize
— Max allowed chunk size based on number of files for glob pattern. This option is only applicable on Windows based systems to avoid command length limitations. See #147globOptions
— { matchBase: true, dot: true }
— micromatch options to
customize how glob patterns match files.ignore
- ['**/docs/**/*.js']
- array of glob patterns to entirely ignore from any task.linters
— Object
— keys (String
) are glob patterns, values (Array<String> | String
) are commands to execute.subTaskConcurrency
— 1
— Controls concurrency for processing chunks generated for each linter. This option is only applicable on Windows. Execution is not concurrent by default(see #225)It is possible to run linters for certain paths only by using glob patterns. micromatch is used to filter the staged files according to these patterns. File patterns should be specified relative to the package.json
location (i.e. where lint-staged
is installed).
NOTE: If you're using lint-staged<5
globs have to be relative to the git root.
{
// .js files anywhere in the project
"*.js": "eslint",
// .js files anywhere in the project
"**/*.js": "eslint",
// .js file in the src directory
"src/*.js": "eslint",
// .js file anywhere within and below the src directory
"src/**/*.js": "eslint",
}
When matching, lint-staged
will do the following
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?
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
is using npm-which to locate locally installed scripts. So in your .lintstagedrc
you can write:
{
"*.js": "eslint --fix"
}
Pass arguments to your commands separated by space as you would do in the shell. See examples below.
Starting from v2.0.0 sequences of commands are supported. Pass an array of commands instead of a single one and they will run sequentially. This is useful for running autoformatting tools like eslint --fix
or stylefmt
but can be used for any arbitrary sequences.
Tools like ESLint/TSLint or stylefmt can reformat your code according to an appropriate config by running eslint --fix
/tslint --fix
. After the code is reformatted, we want it to be added to the same commit. This can be done using following config:
{
"*.js": ["eslint --fix", "git add"]
}
Starting from v3.1, lint-staged will stash you remaining changes (not added to the index) and restore them from stash afterwards. This allows you to create partial commits with hunks using This is still not resolvedgit add --patch
.
All examples assuming you’ve already set up lint-staged and husky in the package.json
.
{
"name": "My project",
"version": "0.1.0",
"scripts": {
"my-custom-script": "linter --arg1 --arg2",
"precommit": "lint-staged"
},
"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.
*.js
and *.jsx
running as a pre-commit hook{
"*.{js,jsx}": "eslint"
}
--fix
and add to commit{
"*.js": ["eslint --fix", "git add"]
}
This will run eslint --fix
and automatically add changes to the commit. Please note, that it doesn’t work well with committing hunks (git add -p
).
If you wish to reuse a npm script defined in your package.json:
{
"*.js": ["npm run my-custom-script --", "git add"]
}
The following is equivalent:
{
"*.js": ["linter --arg1 --arg2", "git add"]
}
prettier
for javascript + flow or typescript{
"*.{js,jsx}": ["prettier --parser flow --write", "git add"]
}
{
"*.{ts,tsx}": ["prettier --parser typescript --write", "git add"]
}
{
"*.css": "stylelint",
"*.scss": "stylelint --syntax=scss"
}
{
"*.scss": ["postcss --config path/to/your/config --replace", "stylelint", "git add"]
}
{
"*.{png,jpeg,jpg,gif,svg}": ["imagemin-lint-staged", "git add"]
}
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.
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:
{
"scripts": {
"precommit": "lint-staged",
"postcommit": "git update-index --again"
}
}
Thanks to this comment for the fix!
lint-staged
in a multi package monorepo?Starting 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.
If you wish to use lint-staged
in a multi package monorepo, it is recommended to install husky
in the root package.json.
lerna
can be used to execute the precommit
script in all sub-packages.
Example repo: sudo-suhas/lint-staged-multi-pkg.
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.
FAQs
Lint files staged by git
The npm package lint-staged receives a total of 0 weekly downloads. As such, lint-staged popularity was classified as not popular.
We found that lint-staged demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.