A Stylelint plugin for webpack that integrates CSS/SCSS linting into the webpack build process
npx @tessl/cli install tessl/npm-stylelint-webpack-plugin@5.0.00
# Stylelint Webpack Plugin
1
2
Stylelint Webpack Plugin integrates Stylelint CSS/SCSS linting into the webpack build process. It enables developers to automatically lint stylesheets during development and build processes, catching CSS errors and enforcing style conventions early in the development workflow.
3
4
## Package Information
5
6
- **Package Name**: stylelint-webpack-plugin
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install stylelint-webpack-plugin --save-dev`
10
11
**Note**: You also need to install `stylelint >= 13` from npm:
12
```bash
13
npm install stylelint --save-dev
14
```
15
16
## Core Imports
17
18
```javascript
19
const StylelintPlugin = require('stylelint-webpack-plugin');
20
```
21
22
For TypeScript:
23
24
```typescript
25
import StylelintWebpackPlugin = require('stylelint-webpack-plugin');
26
```
27
28
## Basic Usage
29
30
```javascript
31
const StylelintPlugin = require('stylelint-webpack-plugin');
32
33
module.exports = {
34
// ...
35
plugins: [
36
new StylelintPlugin({
37
files: ['src/**/*.{css,scss,sass}'],
38
fix: true,
39
}),
40
],
41
// ...
42
};
43
```
44
45
## Architecture
46
47
The plugin is built around several key components:
48
49
- **StylelintWebpackPlugin Class**: Main webpack plugin that integrates with webpack's compilation hooks
50
- **Options Processing**: Validates and merges user options with defaults, separating plugin and stylelint options
51
- **Stylelint Integration**: Manages stylelint instances with caching and optional multi-threading support
52
- **Linting Engine**: Executes linting operations during webpack compilation with result processing
53
- **Error Handling**: Custom error class and webpack error/warning integration
54
55
## Capabilities
56
57
### Plugin Initialization
58
59
Creates a new instance of the Stylelint webpack plugin with configuration options.
60
61
```typescript { .api }
62
class StylelintWebpackPlugin {
63
/**
64
* Creates a new Stylelint webpack plugin instance
65
* @param options - Plugin configuration options
66
*/
67
constructor(options?: Options);
68
69
/**
70
* Webpack plugin apply method - integrates with webpack compilation hooks
71
* @param compiler - Webpack compiler instance
72
*/
73
apply(compiler: Compiler): void;
74
}
75
```
76
77
### Configuration Options
78
79
Comprehensive configuration options for controlling linting behavior, file selection, and output formatting.
80
81
```typescript { .api }
82
interface Options extends Partial<PluginOptions & StylelintOptions> {}
83
84
interface PluginOptions {
85
/** Root directory for files (default: webpack context) */
86
context: string;
87
/** Emit errors to webpack compilation (default: true) */
88
emitError: boolean;
89
/** Emit warnings to webpack compilation (default: true) */
90
emitWarning: boolean;
91
/** Files/directories to exclude (default: ['**/node_modules/**', output.path]) */
92
exclude?: string | string[];
93
/** File extensions to check (default: ['css', 'scss', 'sass']) */
94
extensions: string | string[];
95
/** Fail build on errors (default: true) */
96
failOnError: boolean;
97
/** Fail build on warnings (default: false) */
98
failOnWarning: boolean;
99
/** Files/directories/globs to lint (required for plugin to work) */
100
files: string | string[];
101
/** Output formatter for results */
102
formatter: FormatterType;
103
/** Lint only changed files, skip full lint on start (default: false) */
104
lintDirtyModulesOnly: boolean;
105
/** Process errors only, ignore warnings (default: false) */
106
quiet: boolean;
107
/** Path to stylelint instance (default: 'stylelint') */
108
stylelintPath: string;
109
/** Write output report to file */
110
outputReport: OutputReport;
111
/** Enable multi-threading: true=auto, number=pool size, false/undefined=disabled (default: false) */
112
threads?: number | boolean;
113
}
114
115
interface OutputReport {
116
/** Output file path (relative to webpack output.path) */
117
filePath?: string;
118
/** Formatter for output file (defaults to main formatter) */
119
formatter?: FormatterType;
120
}
121
122
type FormatterType = string | ((results: LintResult[]) => string) | Promise<(results: LintResult[]) => string>;
123
```
124
125
**Usage Examples:**
126
127
```javascript
128
// Basic configuration
129
new StylelintPlugin({
130
files: ['src/**/*.{css,scss}'],
131
});
132
133
// Advanced configuration
134
new StylelintPlugin({
135
context: './src',
136
files: ['**/*.{css,scss,sass}'],
137
exclude: ['vendor/**', 'legacy/**'],
138
fix: true,
139
cache: true,
140
threads: true,
141
failOnError: true,
142
failOnWarning: false,
143
formatter: 'json',
144
outputReport: {
145
filePath: 'stylelint-report.json',
146
formatter: 'json'
147
}
148
});
149
150
// Quiet mode (errors only)
151
new StylelintPlugin({
152
files: ['src/**/*.scss'],
153
quiet: true,
154
emitWarning: false
155
});
156
```
157
158
### Stylelint Options Integration
159
160
All standard Stylelint options are supported and passed through to the stylelint engine.
161
162
```typescript { .api }
163
interface StylelintOptions {
164
/** Use cache to store results (default: true) */
165
cache?: boolean;
166
/** Cache location (default: 'node_modules/.cache/stylelint-webpack-plugin/.stylelintcache') */
167
cacheLocation?: string;
168
/** Configuration object (overrides config files) */
169
config?: Config;
170
/** Path to configuration file */
171
configFile?: string;
172
/** Base directory for configuration file resolution */
173
configBasedir?: string;
174
/** Configuration basename - resolves config relative to this */
175
configBasename?: string;
176
/** Custom syntax module */
177
customSyntax?: string;
178
/** Enable processing when no input files */
179
allowEmptyInput?: boolean;
180
/** Globby options for file pattern matching */
181
globbyOptions?: object;
182
/** Auto-fix problems where possible */
183
fix?: boolean;
184
/** Ignore .stylelintignore files */
185
ignorePath?: string;
186
/** Pattern of files to ignore */
187
ignorePattern?: string[];
188
/** Ignore disable comments */
189
ignoreDisables?: boolean;
190
/** Report needless disable comments */
191
reportNeedlessDisables?: boolean;
192
/** Report invalid scope disable comments */
193
reportInvalidScopeDisables?: boolean;
194
/** Report descending specificity errors */
195
reportDescriptionlessDisables?: boolean;
196
/** Maximum allowed warnings before failing */
197
maxWarnings?: number;
198
/** Disable default ignores */
199
disableDefaultIgnores?: boolean;
200
/** Enable/disable rules based on globs */
201
overrides?: OverrideConfig[];
202
}
203
```
204
205
### Utility Functions
206
207
Configuration processing utilities for separating plugin and stylelint options.
208
209
```typescript { .api }
210
/**
211
* Process and validate plugin options with defaults
212
* @param pluginOptions - User-provided options
213
* @returns Processed plugin options with defaults applied
214
*/
215
function getOptions(pluginOptions: Options): Partial<PluginOptions>;
216
217
/**
218
* Extract stylelint-specific options from combined options
219
* @param pluginOptions - Combined plugin and stylelint options
220
* @returns Stylelint-only options for passing to stylelint
221
*/
222
function getStylelintOptions(pluginOptions: Options): Partial<StylelintOptions>;
223
```
224
225
### Error Handling
226
227
Custom error class for stylelint-specific errors with webpack integration.
228
229
```typescript { .api }
230
class StylelintError extends Error {
231
/**
232
* Creates a stylelint-specific error
233
* @param messages - Error message content
234
*/
235
constructor(messages?: string);
236
237
/** Error name identifier */
238
name: string;
239
/** Empty stack trace (errors come from stylelint) */
240
stack: string;
241
}
242
```
243
244
### Advanced Configuration
245
246
#### Multi-threading Support
247
248
Enable parallel processing for improved performance on large codebases:
249
250
```javascript
251
new StylelintPlugin({
252
files: ['src/**/*.scss'],
253
threads: true, // Auto-detect CPU count
254
// or
255
threads: 4, // Explicit thread count
256
// or
257
threads: false // Disable threading
258
});
259
```
260
261
#### Custom Stylelint Instance
262
263
Use a specific stylelint version or configuration:
264
265
```javascript
266
new StylelintPlugin({
267
files: ['src/**/*.css'],
268
stylelintPath: './custom-stylelint',
269
config: {
270
rules: {
271
'color-no-invalid-hex': true,
272
'declaration-colon-space-after': 'always'
273
}
274
}
275
});
276
```
277
278
#### Watch Mode Integration
279
280
The plugin automatically integrates with webpack's watch mode:
281
282
- **lintDirtyModulesOnly: false** (default): Full lint on initial build and watch runs
283
- **lintDirtyModulesOnly: true**: Skip initial lint, only lint changed files on subsequent builds
284
285
```javascript
286
new StylelintPlugin({
287
files: ['src/**/*.scss'],
288
lintDirtyModulesOnly: true // Only lint changed files in watch mode
289
});
290
```
291
292
## Types
293
294
```typescript { .api }
295
type Compiler = import('webpack').Compiler;
296
type LintResult = import('stylelint').LintResult;
297
type LinterResult = import('stylelint').LinterResult;
298
type LinterOptions = import('stylelint').LinterOptions;
299
type Formatter = import('stylelint').Formatter;
300
301
/** Stylelint configuration object */
302
interface Config {
303
/** Rules configuration */
304
rules?: { [ruleName: string]: any };
305
/** Plugins to load */
306
plugins?: string[];
307
/** Extends configuration */
308
extends?: string | string[];
309
/** Ignore patterns */
310
ignoreFiles?: string | string[];
311
/** Default severity */
312
defaultSeverity?: 'error' | 'warning';
313
/** Custom syntax */
314
customSyntax?: string;
315
}
316
317
/** Override configuration for specific patterns */
318
interface OverrideConfig {
319
/** Files pattern to match */
320
files: string | string[];
321
/** Rules to apply for matched files */
322
rules?: { [ruleName: string]: any };
323
/** Custom syntax for matched files */
324
customSyntax?: string;
325
}
326
```