What is lint-staged?
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.
What are lint-staged's main functionalities?
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"
}
}
}
Other packages similar to lint-staged
pretty-quick
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
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
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.
lint-staged
Lint JS and CSS files staged by git
Motivation
Linting makes more sense when running before commiting you code into repository. In this case you can ensure no :poop: is going put into it and enforce styles.
This repsitory contains 2 shell scrtips that run ESLint and Stylelint against only currently staged files.
Adding pre-commit hooks
To start linting, you have to install a pre-commit hook:
npm install -D pre-commit
- Add
"eslint-staged": "eslint-staged"
to scripts section of package.json (if you want to lint your JS) - Add
"stylelint-staged": "stylelint-staged"
to scripts section of package.json (if you want to lint your CSS) - Add
pre-commit": [ "eslint-staged", "stylelint-staged" ]
to package.json