Stylelint - CSS Linter
What is Stylelint?
Stylelint is a powerful, modern, and extensible linter for CSS, SCSS, Less, and other stylesheet languages. It helps developers identify and fix errors, enforce consistent coding styles, and prevent common mistakes in their stylesheets. By integrating Stylelint into your development workflow, you can significantly improve the quality and maintainability of your CSS code.
Key Features and Usage
Stylelint provides a wide range of rules that can be configured to match your project's specific needs and coding standards. It can be used via its command-line interface (CLI) to lint individual files, entire directories, or even entire projects.
Installation
To get started with Stylelint, you can install it globally using npm:
# Install Stylelint globally
npm install -g stylelint
Initialization
After installation, you can initialize a Stylelint configuration
file in your project. This file (typically named
.stylelintrc.json
, .stylelintrc.js
, or
stylelint.config.js
) defines the rules and settings for
your linter.
# Initialize a Stylelint configuration file in your project
stylelint --init
Linting Files
You can lint a single CSS file or multiple files within a directory. Stylelint supports glob patterns for specifying which files to lint.
# Lint a single CSS file
stylelint styles.css
# Lint multiple CSS files in a directory
stylelint "src/**/*.css"
Automatic Fixing
One of Stylelint's most useful features is its ability to automatically fix many common style errors. This can save a significant amount of time and effort in maintaining code consistency.
# Lint CSS files and automatically fix errors
stylelint "src/**/*.css" --fix
Custom Configurations
Stylelint allows you to use custom configuration files, which is essential for team collaboration and maintaining project-specific standards.
# Lint CSS files and use a specific Stylelint configuration file
stylelint "src/**/*.css" --config custom-config.json
Advanced Options
Stylelint offers several options to control its output and behavior:
-
--verbose
: Enable verbose output for more detailed information. -
--quiet
: Only report errors, suppressing warnings. -
--formatter
: Specify the output format (e.g.,json
,string
). -
--ignore-path
: Specify a file to ignore paths from (e.g.,.stylelintignore
).
# Enable verbose output
stylelint "src/**/*.css" --verbose
# Lint files in quiet mode (only report errors)
stylelint "src/**/*.css" --quiet
# Output results in a different format (e.g., JSON)
stylelint "src/**/*.css" --formatter json
# Output results to a file
stylelint "src/**/*.css" --formatter json > results.json