0
# Svelte Check
1
2
Svelte Check is a command-line tool that provides comprehensive diagnostics for Svelte applications, detecting unused CSS, Svelte accessibility hints, and JavaScript/TypeScript compiler errors. It integrates with TypeScript configuration files and offers flexible output formats for both human consumption and machine processing in CI/CD pipelines.
3
4
## Package Information
5
6
- **Package Name**: svelte-check
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install svelte-check --save-dev`
10
11
## Core Imports
12
13
Svelte Check is primarily used as a CLI tool via the binary:
14
15
```bash
16
# Global installation
17
npm install -g svelte-check
18
svelte-check
19
20
# Local installation (recommended)
21
npm install svelte-check --save-dev
22
npx svelte-check
23
```
24
25
For programmatic usage in build scripts:
26
27
```typescript
28
// Import for programmatic usage (advanced)
29
import { exec } from 'child_process';
30
import { promisify } from 'util';
31
32
const execAsync = promisify(exec);
33
34
// Run svelte-check programmatically
35
const { stdout, stderr } = await execAsync('svelte-check --output machine');
36
```
37
38
## Basic Usage
39
40
### CLI Usage
41
42
Add to your package.json scripts:
43
44
```json
45
{
46
"scripts": {
47
"svelte-check": "svelte-check"
48
}
49
}
50
```
51
52
Run basic check:
53
54
```bash
55
npm run svelte-check
56
```
57
58
With configuration options:
59
60
```bash
61
svelte-check --workspace ./src --output machine --tsconfig ./tsconfig.json
62
```
63
64
### Programmatic Usage
65
66
```typescript
67
// Run svelte-check programmatically via child process
68
import { spawn } from 'child_process';
69
70
function runSvelteCheck(options: string[] = []): Promise<{
71
stdout: string;
72
stderr: string;
73
exitCode: number;
74
}> {
75
return new Promise((resolve) => {
76
const child = spawn('svelte-check', options);
77
let stdout = '';
78
let stderr = '';
79
80
child.stdout.on('data', (data) => stdout += data);
81
child.stderr.on('data', (data) => stderr += data);
82
83
child.on('close', (exitCode) => {
84
resolve({ stdout, stderr, exitCode: exitCode || 0 });
85
});
86
});
87
}
88
89
// Usage
90
const result = await runSvelteCheck(['--workspace', './src', '--output', 'machine']);
91
if (result.exitCode === 0) {
92
console.log('No issues found');
93
} else {
94
console.log('Issues found:', result.stdout);
95
}
96
```
97
98
## Architecture
99
100
Svelte Check is built on top of the Svelte Language Server and integrates several key components:
101
102
- **Language Server Integration**: Uses svelte-language-server for core diagnostic capabilities
103
- **Plugin Architecture**: Leverages TypeScript, Svelte, and CSS plugins for comprehensive checking
104
- **File System Monitoring**: Supports watch mode with efficient file change detection
105
- **Configurable Output**: Multiple output formats for different consumption needs (human/machine)
106
- **TypeScript Integration**: Full TypeScript project support via tsconfig.json
107
108
## Capabilities
109
110
### Command Line Interface
111
112
The primary interface for checking Svelte projects from the command line with extensive configuration options.
113
114
```bash { .api }
115
svelte-check [options]
116
```
117
118
**Available Options:**
119
120
- `--workspace <path>` - Path to workspace directory (default: current working directory)
121
- `--output <format>` - Output format: human, human-verbose, machine, machine-verbose (default: human-verbose)
122
- `--watch` - Watch mode for continuous checking
123
- `--preserveWatchOutput` - Don't clear screen in watch mode
124
- `--tsconfig <path>` - Path to tsconfig or jsconfig file
125
- `--no-tsconfig` - Only check Svelte files, ignore JS/TS files
126
- `--ignore <paths>` - Files/folders to ignore, relative to workspace root, comma-separated, inside quotes (only with --no-tsconfig)
127
- `--fail-on-warnings` - Exit with error code when warnings are found
128
- `--compiler-warnings <codes>` - Configure Svelte compiler warning levels
129
- `--diagnostic-sources <sources>` - Limit diagnostic sources: js,svelte,css
130
- `--threshold <level>` - Filter diagnostics: error, warning
131
- `--color` - Force enable color output
132
- `--no-color` - Force disable color output
133
134
**Usage Examples:**
135
136
```bash
137
# Basic check
138
svelte-check
139
140
# Check specific workspace with TypeScript config
141
svelte-check --workspace ./src --tsconfig ./tsconfig.json
142
143
# Machine-readable output for CI
144
svelte-check --output machine --fail-on-warnings
145
146
# Watch mode with custom ignore patterns
147
svelte-check --watch --ignore "dist,build" --no-tsconfig
148
149
# Configure compiler warnings
150
svelte-check --compiler-warnings "css-unused-selector:ignore,unused-export-let:error"
151
152
# Filter diagnostic sources
153
svelte-check --diagnostic-sources "js,svelte" --threshold error
154
```
155
156
### Programmatic Integration
157
158
For build tool integration and programmatic usage via child process execution.
159
160
```typescript { .api }
161
/**
162
* Run svelte-check programmatically
163
* @param args - Command line arguments array
164
* @returns Promise resolving to execution result
165
*/
166
function runSvelteCheck(args: string[]): Promise<SvelteCheckResult>;
167
168
/**
169
* Result of svelte-check execution
170
*/
171
interface SvelteCheckResult {
172
/** Standard output from svelte-check */
173
stdout: string;
174
/** Standard error output */
175
stderr: string;
176
/** Exit code (0 for success, 1 for errors/warnings) */
177
exitCode: number;
178
}
179
180
/**
181
* Parse machine-readable output from svelte-check
182
* @param output - Machine format output string
183
* @returns Parsed diagnostic results
184
*/
185
function parseMachineOutput(output: string): ParsedDiagnostic[];
186
187
/**
188
* Parsed diagnostic from machine output
189
*/
190
interface ParsedDiagnostic {
191
/** Diagnostic type */
192
type: 'ERROR' | 'WARNING';
193
/** File path relative to workspace */
194
filename: string;
195
/** Line number (1-based) */
196
line: number;
197
/** Character position (1-based) */
198
character: number;
199
/** Diagnostic message */
200
message: string;
201
/** Diagnostic timestamp */
202
timestamp: number;
203
}
204
205
/**
206
* Individual diagnostic issue (from language server protocol)
207
*/
208
interface Diagnostic {
209
/** Source location range */
210
range: Range;
211
/** Issue severity level */
212
severity: DiagnosticSeverity;
213
/** Human-readable error message */
214
message: string;
215
/** Error/warning code */
216
code?: number | string;
217
/** Diagnostic source (e.g., "svelte", "typescript") */
218
source?: string;
219
/** Additional diagnostic tags */
220
tags?: DiagnosticTag[];
221
}
222
223
/**
224
* Position range in source code
225
*/
226
interface Range {
227
start: Position;
228
end: Position;
229
}
230
231
/**
232
* Line and character position
233
*/
234
interface Position {
235
/** Zero-based line number */
236
line: number;
237
/** Zero-based character offset */
238
character: number;
239
}
240
241
/**
242
* Diagnostic tag for additional metadata
243
*/
244
interface DiagnosticTag {
245
/** Tag type identifier */
246
type: number;
247
}
248
```
249
250
### Output Writers
251
252
Customizable output formatting for different consumption needs.
253
254
```typescript { .api }
255
/**
256
* Base interface for diagnostic output writers
257
*/
258
interface Writer {
259
/** Initialize writer with workspace directory */
260
start(workspaceDir: string): void;
261
/** Write diagnostics for a single file */
262
file(diagnostics: Diagnostic[], workspaceDir: string, filename: string, text: string): void;
263
/** Write completion summary */
264
completion(fileCount: number, errorCount: number, warningCount: number, fileCountWithProblems: number): void;
265
/** Write failure message */
266
failure(err: Error): void;
267
}
268
269
/**
270
* Human-readable console output writer
271
*/
272
class HumanFriendlyWriter implements Writer {
273
constructor(
274
stream: Writable,
275
isVerbose?: boolean,
276
isWatchMode?: boolean,
277
clearScreen?: boolean,
278
diagnosticFilter?: DiagnosticFilter
279
);
280
}
281
282
/**
283
* Machine-readable structured output writer
284
*/
285
class MachineFriendlyWriter implements Writer {
286
constructor(
287
stream: Writable,
288
isVerbose?: boolean,
289
diagnosticFilter?: DiagnosticFilter
290
);
291
}
292
293
/**
294
* Function to filter which diagnostics to include in output
295
*/
296
type DiagnosticFilter = (diagnostic: Diagnostic) => boolean;
297
298
/** Default filter that includes all diagnostics */
299
const DEFAULT_FILTER: DiagnosticFilter;
300
```
301
302
### CLI Option Parsing
303
304
Internal option parsing functionality for command-line interface.
305
306
```typescript { .api }
307
/**
308
* Parsed CLI options structure
309
*/
310
interface SvelteCheckCliOptions {
311
/** Workspace URI object */
312
workspaceUri: URI;
313
/** Selected output format */
314
outputFormat: OutputFormat;
315
/** Watch mode enabled */
316
watch: boolean;
317
/** Preserve output in watch mode */
318
preserveWatchOutput: boolean;
319
/** TypeScript config file path */
320
tsconfig?: string;
321
/** File paths to ignore */
322
filePathsToIgnore: string[];
323
/** Fail on warnings flag */
324
failOnWarnings: boolean;
325
/** Compiler warning configuration */
326
compilerWarnings: Record<string, 'error' | 'ignore'>;
327
/** Enabled diagnostic sources */
328
diagnosticSources: DiagnosticSource[];
329
/** Diagnostic threshold level */
330
threshold: Threshold;
331
}
332
333
```
334
335
## Types
336
337
```typescript { .api }
338
/** Supported output formats */
339
type OutputFormat = "human" | "human-verbose" | "machine" | "machine-verbose";
340
341
/** Available diagnostic sources */
342
type SvelteCheckDiagnosticSource = "js" | "css" | "svelte";
343
344
/** Diagnostic source type alias */
345
type DiagnosticSource = "js" | "css" | "svelte";
346
347
/** Diagnostic threshold levels */
348
type Threshold = "warning" | "error";
349
350
/** Diagnostic severity levels */
351
enum DiagnosticSeverity {
352
Error = 1,
353
Warning = 2,
354
Information = 3,
355
Hint = 4
356
}
357
358
/** URI class for file system paths */
359
class URI {
360
static file(path: string): URI;
361
readonly fsPath: string;
362
toString(): string;
363
}
364
```
365
366
## Error Handling
367
368
Svelte Check reports various types of issues:
369
370
**JavaScript/TypeScript Errors:**
371
- Syntax errors
372
- Type checking errors
373
- Import resolution failures
374
- Missing type declarations
375
376
**Svelte Component Errors:**
377
- Component compilation errors
378
- Invalid Svelte syntax
379
- Unused export properties
380
- Accessibility warnings
381
382
**CSS Errors:**
383
- Unused CSS selectors
384
- CSS syntax errors
385
- SCSS/PostCSS compilation errors
386
387
**Configuration Errors:**
388
- Invalid TypeScript configuration
389
- Missing or invalid workspace paths
390
- File access permissions
391
392
## Machine Output Format
393
394
### Standard Format (`--output machine`)
395
396
Timestamp-prefixed space-separated format:
397
398
```
399
1590680325583 START "/path/to/workspace"
400
1590680326283 ERROR "component.svelte" 1:16 "Type error message"
401
1590680326778 WARNING "component.svelte" 0:37 "Warning message"
402
1590680326807 COMPLETED 20 FILES 21 ERRORS 1 WARNINGS 3 FILES_WITH_PROBLEMS
403
```
404
405
### Verbose Format (`--output machine-verbose`)
406
407
Timestamp-prefixed JSON format:
408
409
```
410
1590680326283 {"type":"ERROR","filename":"component.svelte","start":{"line":1,"character":16},"end":{"line":1,"character":23},"message":"Type error message","code":2307,"source":"js"}
411
1590680326778 {"type":"WARNING","filename":"component.svelte","start":{"line":0,"character":37},"end":{"line":0,"character":51},"message":"Warning message","code":"unused-export-let","source":"svelte"}
412
```
413
414
## Integration Examples
415
416
### CI/CD Pipeline
417
418
```bash
419
# Exit with error code on any issues
420
svelte-check --output machine --fail-on-warnings
421
422
# Check only errors for faster CI
423
svelte-check --threshold error --diagnostic-sources "js,svelte"
424
```
425
426
### Build Tool Integration
427
428
```typescript
429
import { exec } from 'child_process';
430
import { promisify } from 'util';
431
432
const execAsync = promisify(exec);
433
434
export async function runSvelteCheck(workspacePath: string) {
435
try {
436
const { stdout, stderr } = await execAsync(
437
`svelte-check --workspace "${workspacePath}" --output machine --fail-on-warnings`
438
);
439
console.log('Svelte check passed');
440
return { success: true, output: stdout };
441
} catch (error: any) {
442
console.error('Svelte check failed:', error.stdout || error.message);
443
throw new Error('Svelte check failed with errors');
444
}
445
}
446
```
447
448
### Watch Mode Integration
449
450
```typescript
451
// Watch mode via CLI in a separate process
452
const watcher = spawn('svelte-check', ['--watch', '--workspace', workspacePath]);
453
454
watcher.stdout.on('data', (data) => {
455
console.log('Diagnostics updated:', data.toString());
456
});
457
458
watcher.on('close', (code) => {
459
console.log('Watch mode ended with code:', code);
460
});
461
```