0
# Programmatic API
1
2
Core linting functionality for processing CSS code and files programmatically. The main API for integrating Stylelint into applications, build processes, and development tools.
3
4
## Capabilities
5
6
### Lint Function
7
8
Main programmatic API for linting CSS code and files. Supports both string-based CSS and file system operations.
9
10
```typescript { .api }
11
/**
12
* Lint CSS code or files
13
* @param options - Linting configuration and input
14
* @returns Promise resolving to linting results
15
*/
16
function lint(options: LinterOptions): Promise<LinterResult>;
17
18
interface LinterOptions {
19
/** File paths or glob patterns to lint */
20
files?: string | string[];
21
/** Options for globby when resolving file patterns */
22
globbyOptions?: GlobbyOptions;
23
/** CSS code string to lint directly */
24
code?: string;
25
/** Optional filename for code-based linting */
26
codeFilename?: string;
27
/** Stylelint configuration object */
28
config?: Config;
29
/** Path to configuration file */
30
configFile?: string;
31
/** Base directory for resolving configuration */
32
configBasedir?: string;
33
/** Working directory for file operations */
34
cwd?: string;
35
/** Enable automatic fixing where possible */
36
fix?: boolean | FixMode;
37
/** Compute edit info for fixes */
38
computeEditInfo?: boolean;
39
/** Output formatter type or custom formatter */
40
formatter?: FormatterType | Formatter;
41
/** Cache results for improved performance */
42
cache?: boolean;
43
/** Cache location path */
44
cacheLocation?: string;
45
/** Cache strategy */
46
cacheStrategy?: string;
47
/** Maximum number of warnings before failing */
48
maxWarnings?: number;
49
/** Ignore disable comments */
50
ignoreDisables?: boolean;
51
/** Ignore file paths */
52
ignorePath?: string | string[];
53
/** Ignore patterns for files */
54
ignorePattern?: string[];
55
/** Custom syntax for non-standard CSS */
56
customSyntax?: CustomSyntax;
57
/** Disable default ignore patterns */
58
disableDefaultIgnores?: boolean;
59
/** Enable quiet mode (errors only) */
60
quiet?: boolean;
61
/** Quiet deprecation warnings */
62
quietDeprecationWarnings?: boolean;
63
/** Allow empty input without error */
64
allowEmptyInput?: boolean;
65
/** Report descriptionless disable comments */
66
reportDescriptionlessDisables?: boolean;
67
/** Report needless disable comments */
68
reportNeedlessDisables?: boolean;
69
/** Report invalid scope disable comments */
70
reportInvalidScopeDisables?: boolean;
71
/** Report unscoped disable comments */
72
reportUnscopedDisables?: boolean;
73
/** Force enable/disable validation of rule options */
74
validate?: boolean;
75
}
76
```
77
78
**Usage Examples:**
79
80
```javascript
81
import stylelint from "stylelint";
82
const { lint } = stylelint;
83
84
// Lint CSS code string
85
const result = await lint({
86
code: `
87
.example {
88
color: #ffffff;
89
font-weight: bold;
90
}
91
`,
92
config: {
93
rules: {
94
"color-hex-length": "short",
95
"font-weight-notation": "numeric"
96
}
97
}
98
});
99
100
// Lint files
101
const fileResult = await lint({
102
files: ["src/**/*.css", "!src/vendor/**"],
103
configFile: ".stylelintrc.json",
104
fix: true
105
});
106
107
// Lint with custom formatter
108
const jsonResult = await lint({
109
files: "styles/*.scss",
110
formatter: "json",
111
customSyntax: "postcss-scss"
112
});
113
```
114
115
### Linter Result
116
117
Result object returned by the lint function containing all linting information and formatted output.
118
119
```typescript { .api }
120
interface LinterResult {
121
/** Working directory from which linter was run */
122
cwd: string;
123
/** Array of individual file results */
124
results: LintResult[];
125
/** Whether any errors were found */
126
errored: boolean;
127
/** Formatted report string */
128
report: string;
129
/** Autofixed code (when fix option is enabled) */
130
code?: string;
131
/** @deprecated Use report instead */
132
output: string;
133
/** Information about max warnings exceeded */
134
maxWarningsExceeded?: {
135
maxWarnings: number;
136
foundWarnings: number;
137
};
138
/** Reports on disable comment usage */
139
reportedDisables: DisableReportEntry[];
140
needlessDisables?: DisableReportEntry[];
141
invalidScopeDisables?: DisableReportEntry[];
142
descriptionlessDisables?: DisableReportEntry[];
143
/** Rule metadata information */
144
ruleMetadata: { [ruleName: string]: Partial<RuleMeta> };
145
}
146
```
147
148
### Individual File Result
149
150
Result for a single file or code string containing warnings, errors, and metadata.
151
152
```typescript { .api }
153
interface LintResult {
154
/** File path or undefined for code-based linting */
155
source?: string;
156
/** Array of linting warnings and errors */
157
warnings: Warning[];
158
/** Whether this file had any errors */
159
errored?: boolean;
160
/** Whether this file was ignored */
161
ignored?: boolean;
162
/** Deprecation warnings */
163
deprecations: {
164
text: string;
165
reference?: string;
166
}[];
167
/** Invalid option warnings */
168
invalidOptionWarnings: {
169
text: string;
170
}[];
171
/** CSS parse errors */
172
parseErrors: (PostCSS.Warning & {
173
stylelintType: 'parseError';
174
})[];
175
}
176
```
177
178
### Warning Object
179
180
Individual warning or error from linting rules.
181
182
```typescript { .api }
183
interface Warning {
184
/** Line number of the issue */
185
line: number;
186
/** Column number of the issue */
187
column: number;
188
/** End line number (for ranges) */
189
endLine?: number;
190
/** End column number (for ranges) */
191
endColumn?: number;
192
/** Rule name that generated this warning */
193
rule: string;
194
/** Severity level */
195
severity: 'warning' | 'error';
196
/** Human-readable message text */
197
text: string;
198
/** URL to rule documentation */
199
url?: string;
200
/** Auto-fix information if available */
201
fix?: EditInfo;
202
}
203
```
204
205
### Fix Modes
206
207
Different modes for automatic fixing behavior.
208
209
```typescript { .api }
210
type FixMode = 'lax' | 'strict';
211
212
interface EditInfo {
213
/** Start and end positions for the fix */
214
range: [number, number];
215
/** Replacement text */
216
text: string;
217
}
218
```
219
220
### Custom Syntax Support
221
222
Support for non-standard CSS syntaxes like SCSS, Less, and CSS-in-JS.
223
224
```typescript { .api }
225
type CustomSyntax = string | PostCSS.Syntax;
226
227
// Examples of custom syntax usage
228
const scssResult = await lint({
229
files: "src/**/*.scss",
230
customSyntax: "postcss-scss"
231
});
232
233
const lessResult = await lint({
234
files: "src/**/*.less",
235
customSyntax: "postcss-less"
236
});
237
```
238
239
### Error Handling
240
241
Common error scenarios and handling patterns.
242
243
```javascript
244
try {
245
const result = await lint({
246
code: invalidCSS,
247
config: { rules: { "color-no-invalid-hex": true } }
248
});
249
250
if (result.errored) {
251
console.error("Linting failed:");
252
result.results.forEach(fileResult => {
253
fileResult.warnings.forEach(warning => {
254
if (warning.severity === 'error') {
255
console.error(`${warning.rule}: ${warning.text}`);
256
}
257
});
258
});
259
}
260
} catch (error) {
261
console.error("Linting error:", error.message);
262
}
263
```