A mighty CSS linter that helps you avoid errors and enforce conventions.
npx @tessl/cli install tessl/npm-stylelint@16.23.00
# Stylelint
1
2
Stylelint is a comprehensive CSS linting tool that helps developers avoid errors and enforce consistent coding conventions across CSS, SCSS, Sass, Less, and SugarSS stylesheets. It features over 100 built-in rules for modern CSS syntax validation, supports custom plugins for extending functionality, provides automatic fixing capabilities where possible, and offers shareable configuration presets.
3
4
## Package Information
5
6
- **Package Name**: stylelint
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install stylelint`
10
11
## Core Imports
12
13
```javascript
14
import stylelint from "stylelint";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const stylelint = require("stylelint");
21
```
22
23
Named imports:
24
25
```javascript
26
import { lint, rules, formatters, createPlugin, resolveConfig, utils } from "stylelint";
27
```
28
29
Note: Named imports are not directly supported - use default import and destructure:
30
31
```javascript
32
import stylelint from "stylelint";
33
const { lint, rules, formatters, createPlugin, resolveConfig, utils } = stylelint;
34
```
35
36
## Basic Usage
37
38
```javascript
39
import stylelint from "stylelint";
40
41
// Lint CSS code
42
const result = await stylelint.lint({
43
code: `
44
.example {
45
color: #ffffff;
46
font-weight: bold;
47
}
48
`,
49
config: {
50
rules: {
51
"color-hex-length": "short",
52
"font-weight-notation": "numeric"
53
}
54
}
55
});
56
57
console.log(result.results[0].warnings);
58
```
59
60
## Architecture
61
62
Stylelint is built around several key components:
63
64
- **Linting Engine**: Core linting functionality that processes CSS and applies rules
65
- **Rule System**: 139+ built-in rules covering all aspects of CSS validation and conventions
66
- **Plugin System**: Extensible architecture for custom rules and functionality
67
- **Configuration System**: Flexible configuration with extends, overrides, and shareable configs
68
- **Formatters**: Various output formats for integration with different tools and workflows
69
- **PostCSS Integration**: Built on PostCSS for robust CSS parsing and manipulation
70
- **CLI Interface**: Command-line tool for file system integration and automation
71
72
## Capabilities
73
74
### Programmatic Linting
75
76
Core linting functionality for processing CSS code and files programmatically. The main API for integrating Stylelint into applications and build processes.
77
78
```typescript { .api }
79
function lint(options: LinterOptions): Promise<LinterResult>;
80
81
interface LinterOptions {
82
files?: string | string[];
83
code?: string;
84
config?: Config;
85
configFile?: string;
86
fix?: boolean;
87
formatter?: FormatterType | Formatter;
88
cwd?: string;
89
}
90
91
interface LinterResult {
92
results: LintResult[];
93
errored: boolean;
94
report: string;
95
code?: string;
96
cwd: string;
97
}
98
```
99
100
[Programmatic API](./programmatic-api.md)
101
102
### Built-in Rules
103
104
Complete collection of 139+ built-in rules for CSS validation and convention enforcement. Rules are categorized by CSS features and provide comprehensive coverage of modern CSS.
105
106
```typescript { .api }
107
const rules: { readonly [name in keyof CoreRules]: Promise<CoreRules[name]> };
108
109
// Example rule types
110
type ColorHexLengthRule = Rule<'short' | 'long', {}, AutofixMessage>;
111
type PropertyNoUnknownRule = Rule<true, {
112
ignoreProperties: string[];
113
checkPrefixed: boolean;
114
}, RejectedMessage<[property: string]>>;
115
```
116
117
[Built-in Rules](./built-in-rules.md)
118
119
### Configuration System
120
121
Comprehensive configuration system supporting extends, plugins, rule settings, and file-specific overrides. Enables both simple and complex linting setups.
122
123
```typescript { .api }
124
interface Config {
125
extends?: string | string[];
126
plugins?: (string | Plugin)[];
127
rules?: { [ruleName: string]: ConfigRuleSettings<any, Object> };
128
ignoreFiles?: string | string[];
129
overrides?: ConfigOverride[];
130
customSyntax?: CustomSyntax;
131
}
132
133
function resolveConfig(
134
filePath: string,
135
options?: Pick<LinterOptions, 'cwd' | 'config' | 'configBasedir' | 'configFile'>
136
): Promise<Config | undefined>;
137
```
138
139
[Configuration](./configuration.md)
140
141
### Plugin Development
142
143
Plugin system for creating custom rules and extending Stylelint functionality. Provides utilities for rule creation, validation, and integration.
144
145
```typescript { .api }
146
function createPlugin(ruleName: string, rule: Rule): Plugin;
147
148
interface Plugin {
149
ruleName: string;
150
rule: Rule;
151
}
152
153
interface Rule<P = any, S = any, M = RuleMessages> {
154
(primaryOption: P, secondaryOptions: S, context: RuleContext):
155
(root: PostCSS.Root, result: PostcssResult) => Promise<void> | void;
156
ruleName: string;
157
messages: M;
158
meta?: RuleMeta;
159
}
160
```
161
162
[Plugin Development](./plugin-development.md)
163
164
### Output Formatting
165
166
Multiple output formatters for different integration needs, from human-readable reports to machine-parsable formats.
167
168
```typescript { .api }
169
interface Formatters {
170
readonly compact: Promise<Formatter>;
171
readonly github: Promise<Formatter>;
172
readonly json: Promise<Formatter>;
173
readonly string: Promise<Formatter>;
174
readonly tap: Promise<Formatter>;
175
readonly unix: Promise<Formatter>;
176
readonly verbose: Promise<Formatter>;
177
}
178
179
type Formatter = (results: LintResult[], returnValue: LinterResult) => string;
180
```
181
182
### PostCSS Integration
183
184
PostCSS plugin interface for seamless integration into PostCSS processing pipelines and build tools.
185
186
```typescript { .api }
187
// stylelint as PostCSS plugin - the default export is a PostCSS plugin
188
const postcssPlugin: PostCSS.PluginCreator<PostcssPluginOptions>;
189
190
type PostcssPluginOptions = Omit<LinterOptions, 'customSyntax'> | Config;
191
```
192
193
### Utility Functions
194
195
Developer utilities for rule creation, validation, and CSS processing. Essential tools for plugin authors and advanced usage scenarios.
196
197
```typescript { .api }
198
interface Utils {
199
report: (problem: Problem) => void;
200
ruleMessages: <T extends RuleMessages>(ruleName: string, messages: T) => T;
201
validateOptions: (result: PostcssResult, ruleName: string, ...options: RuleOptions[]) => boolean;
202
checkAgainstRule: <T, O extends Object>(options: CheckAgainstRuleOptions<T, O>, callback: (warning: PostCSS.Warning) => void) => Promise<void>;
203
}
204
```
205
206
### Reference Utilities
207
208
Complete collection of CSS reference data used by stylelint rules for property analysis, validation, and categorization.
209
210
```typescript { .api }
211
interface Reference {
212
/** Map of shorthand properties to their longhand sub-properties */
213
longhandSubPropertiesOfShorthandProperties: LonghandSubPropertiesOfShorthandProperties;
214
/** Properties that accept custom identifiers */
215
acceptCustomIdentsProperties: ReadonlySet<string>;
216
/** Map of shorthand properties to properties they reset to initial values */
217
shorthandToResetToInitialProperty: ReadonlyMap<string, ReadonlySet<string>>;
218
/** Properties that accept single color values */
219
singleValueColorProperties: ReadonlySet<string>;
220
/** Properties that accept multiple color values */
221
multiValueColorProperties: ReadonlySet<string>;
222
/** All color-related properties (single and multi-value) */
223
colorProperties: ReadonlySet<string>;
224
/** Longhand properties that accept time values */
225
longhandTimeProperties: ReadonlySet<string>;
226
/** Shorthand properties that accept time values */
227
shorthandTimeProperties: ReadonlySet<string>;
228
/** Properties valid in @page context */
229
pageContextProperties: ReadonlySet<string>;
230
/** Properties valid in margin context */
231
marginContextProperties: ReadonlySet<string>;
232
}
233
234
type LonghandSubPropertiesOfShorthandProperties = ReadonlyMap<string, ReadonlySet<string>>;
235
```
236
237
## Types
238
239
```typescript { .api }
240
interface LintResult {
241
source?: string;
242
warnings: Warning[];
243
errored?: boolean;
244
ignored?: boolean;
245
deprecations: { text: string; reference?: string }[];
246
invalidOptionWarnings: { text: string }[];
247
parseErrors: (PostCSS.Warning & { stylelintType: 'parseError' })[];
248
}
249
250
interface Warning {
251
line: number;
252
column: number;
253
endLine?: number;
254
endColumn?: number;
255
rule: string;
256
severity: 'warning' | 'error';
257
text: string;
258
url?: string;
259
fix?: EditInfo;
260
}
261
262
interface EditInfo {
263
range: [number, number];
264
text: string;
265
}
266
267
type Severity = 'warning' | 'error';
268
269
type ConfigRuleSettings<T, O extends Object> =
270
| null
271
| undefined
272
| NonNullable<T>
273
| [NonNullable<T>]
274
| [NonNullable<T>, O];
275
276
interface Position {
277
line: number;
278
column: number;
279
}
280
281
interface Range {
282
start: Position;
283
end: Position;
284
}
285
286
interface CssSyntaxError {
287
file?: string;
288
input: {
289
column: number;
290
file?: string;
291
line: number;
292
source: string;
293
};
294
line: number;
295
column: number;
296
endLine?: number;
297
endColumn?: number;
298
message: string;
299
name: string;
300
reason: string;
301
source: string;
302
}
303
304
interface DisableReportRange {
305
rule: string;
306
start: number;
307
end?: number;
308
}
309
310
interface DisableReportEntry {
311
source?: string;
312
ranges: DisableReportRange[];
313
}
314
315
type DisableOptionsReport = DisableReportEntry[];
316
317
interface LanguageOptions {
318
syntax?: {
319
atRules?: Record<string, {
320
comment?: string;
321
prelude?: string;
322
descriptors?: Record<string, string>;
323
}>;
324
cssWideKeywords?: string[];
325
properties?: Record<string, string>;
326
types?: Record<string, string>;
327
};
328
}
329
330
interface InternalApi {
331
_options: LinterOptions & { cwd: string };
332
_extendExplorer: any; // cosmiconfig explorer
333
_specifiedConfigCache: Map<Config, Map<string, any>>;
334
_postcssResultCache: Map<string, any>; // PostCSS.Result
335
_fileCache: FileCache;
336
}
337
338
interface FileCache {
339
calcHashOfConfig: (config: Config) => void;
340
hasFileChanged: (absoluteFilepath: string) => boolean;
341
reconcile: () => void;
342
destroy: () => void;
343
removeEntry: (absoluteFilepath: string) => void;
344
}
345
```