0
# Error Handling
1
2
Size Limit provides comprehensive error handling with specific error types, helpful messages, and configuration examples for common issues.
3
4
## Capabilities
5
6
### SizeLimitError Class
7
8
The main error class for Size Limit specific errors with structured messaging.
9
10
```javascript { .api }
11
class SizeLimitError extends Error {
12
constructor(type: string, ...args: any[]);
13
name: "SizeLimitError";
14
example?: string; // Configuration example for certain error types
15
}
16
```
17
18
**Usage Examples:**
19
20
```javascript
21
import { SizeLimitError } from "size-limit";
22
23
try {
24
// Size Limit operation that might fail
25
await sizeLimit(plugins, config);
26
} catch (error) {
27
if (error instanceof SizeLimitError) {
28
console.error(`Size Limit Error: ${error.message}`);
29
30
// Show configuration example if available
31
if (error.example) {
32
console.log("Example configuration:");
33
console.log(error.example);
34
}
35
} else {
36
// Handle other errors
37
console.error("Unexpected error:", error);
38
}
39
}
40
```
41
42
### Error Types and Messages
43
44
Size Limit defines specific error types with helpful messages and context.
45
46
```javascript { .api }
47
// Configuration Errors
48
const ERROR_TYPES = {
49
// Missing or invalid configuration
50
noConfig: () => "Create Size Limit config in *package.json*",
51
emptyConfig: () => "Size Limit config must *not be empty*",
52
noArrayConfig: () => "Size Limit config must contain *an array*",
53
noObjectCheck: () => "Size Limit config array should contain *only objects*",
54
55
// Path configuration errors
56
pathNotString: () =>
57
"The *path* in Size Limit config must be *a string* or *an array of strings*",
58
59
// Entry configuration errors
60
entryNotString: () =>
61
"The *entry* in Size Limit config must be *a string* or *an array of strings*",
62
63
// Missing package.json
64
noPackage: () =>
65
"Size Limit didn't find *package.json*. Create npm package and run Size Limit there.",
66
67
// Plugin errors
68
missedPlugin: (mod) => `Add *@size-limit/${mod}* plugin to Size Limit`,
69
pluginlessConfig: (opt, mod) =>
70
`Config option *${opt}* needs *@size-limit/${mod}* plugin`,
71
multiPluginlessConfig: (opt, mod1, mod2) =>
72
`Config option *${opt}* needs *@size-limit/${mod1}* or *@size-limit/${mod2}* plugin`,
73
timeWithoutPlugin: () => "Add *@size-limit/time* plugin to use time limit",
74
75
// Command line argument errors
76
unknownArg: (arg) =>
77
`Unknown argument *${arg}*. Check command for typo and read docs.`,
78
argWithoutParameter: (arg, parameter) =>
79
`Missing parameter *${parameter}* for *--${arg}* argument`,
80
argWithoutPlugins: (arg, mod1, mod2) =>
81
`Argument *--${arg}* needs *@size-limit/${mod1}* or *@size-limit/${mod2}* plugin`,
82
argWithoutAnalyzer: (arg, bundler, analyzer) =>
83
`Argument *--${arg}* works only with *@size-limit/${bundler}* plugin and *@size-limit/${analyzer}* plugin`,
84
argWithoutAnotherArg: (arg, anotherArg) =>
85
`Argument *--${arg}* works only with *--${anotherArg}* argument`,
86
87
// Build and file errors
88
bundleDirNotEmpty: (dir) =>
89
`The directory *${dir}* is not empty. Pass *--clean-dir* if you want to remove it`,
90
unknownEntry: (entry) =>
91
`Size Limit didn't find *${entry}* entry in the custom bundler config`,
92
93
// Configuration validation errors
94
unknownOption: (opt) =>
95
`Unknown option *${opt}* in config. Check Size Limit docs and version.`,
96
97
// Command execution errors
98
cmdError: (cmd, error) =>
99
error ? `${cmd} error: ${error}` : `${cmd} error`
100
};
101
```
102
103
### Configuration Examples for Errors
104
105
Certain error types include configuration examples to help users fix issues.
106
107
```javascript { .api }
108
// Errors that include configuration examples
109
const ERRORS_WITH_EXAMPLES = [
110
"emptyConfig",
111
"noArrayConfig",
112
"noConfig",
113
"noObjectCheck",
114
"pathNotString"
115
];
116
117
// Example configuration shown for these errors:
118
const EXAMPLE_CONFIG = ` "size-limit": [
119
{
120
"path": "dist/bundle.js",
121
"limit": "10 kB"
122
}
123
]`;
124
```
125
126
**Error Example Output:**
127
128
```bash
129
# When configuration is missing
130
Error: Create Size Limit config in package.json
131
132
Example configuration:
133
"size-limit": [
134
{
135
"path": "dist/bundle.js",
136
"limit": "10 kB"
137
}
138
]
139
```
140
141
### Common Error Scenarios
142
143
Typical error scenarios and their solutions.
144
145
#### Missing Configuration
146
147
```javascript { .api }
148
// Error: No configuration found
149
// Cause: No size-limit config in package.json or config files
150
// Solution: Add configuration to package.json
151
```
152
153
**Example Fix:**
154
155
```json
156
{
157
"name": "my-package",
158
"size-limit": [
159
{
160
"path": "dist/bundle.js",
161
"limit": "10 kB"
162
}
163
]
164
}
165
```
166
167
#### Missing Plugin Dependencies
168
169
```javascript { .api }
170
// Error: Add @size-limit/webpack plugin to Size Limit
171
// Cause: Configuration uses webpack features but plugin not installed
172
// Solution: Install required plugin
173
```
174
175
**Example Fix:**
176
177
```bash
178
npm install --save-dev @size-limit/webpack
179
```
180
181
#### Invalid Configuration Format
182
183
```javascript { .api }
184
// Error: Size Limit config must contain an array
185
// Cause: Configuration is not an array of check objects
186
// Solution: Use array format for configuration
187
```
188
189
**Example Fix:**
190
191
```json
192
{
193
"size-limit": [
194
{
195
"path": "dist/bundle.js",
196
"limit": "10 kB"
197
}
198
]
199
}
200
```
201
202
#### Path Configuration Errors
203
204
```javascript { .api }
205
// Error: The path in Size Limit config must be a string or an array of strings
206
// Cause: Invalid path value (not string or string array)
207
// Solution: Use proper path format
208
```
209
210
**Example Fix:**
211
212
```json
213
{
214
"size-limit": [
215
{
216
"path": ["dist/app.js", "dist/vendor.js"],
217
"limit": "100 kB"
218
}
219
]
220
}
221
```
222
223
#### Plugin Compatibility Errors
224
225
```javascript { .api }
226
// Error: Config option webpack needs @size-limit/webpack plugin
227
// Cause: Configuration uses plugin-specific options without plugin installed
228
// Solution: Install required plugin or remove incompatible options
229
```
230
231
#### Command Line Argument Errors
232
233
```javascript { .api }
234
// Error: Unknown argument --invalid-flag
235
// Cause: Typo in command line argument
236
// Solution: Check argument spelling and available options
237
```
238
239
**Example Fix:**
240
241
```bash
242
# Wrong
243
size-limit --invalid-flag
244
245
# Correct
246
size-limit --json
247
```
248
249
### Error Handling Best Practices
250
251
Guidelines for handling Size Limit errors in applications.
252
253
**Programmatic API Error Handling:**
254
255
```javascript
256
import sizeLimit, { SizeLimitError } from "size-limit";
257
258
try {
259
const results = await sizeLimit(plugins, config);
260
console.log("Size check passed:", results);
261
} catch (error) {
262
if (error instanceof SizeLimitError) {
263
// Handle Size Limit specific errors
264
console.error("Configuration Error:", error.message);
265
266
if (error.example) {
267
console.log("Try this configuration:");
268
console.log(error.example);
269
}
270
271
// Exit with specific code for CI
272
process.exit(1);
273
} else {
274
// Handle unexpected errors
275
console.error("Unexpected error:", error);
276
process.exit(2);
277
}
278
}
279
```
280
281
**CLI Error Handling:**
282
283
```bash
284
# Check exit codes in scripts
285
if npx size-limit --silent; then
286
echo "Size limits passed"
287
else
288
exit_code=$?
289
if [ $exit_code -eq 1 ]; then
290
echo "Size limit exceeded or configuration error"
291
else
292
echo "Unexpected error occurred"
293
fi
294
exit $exit_code
295
fi
296
```
297
298
### Debugging Tips
299
300
Tips for debugging Size Limit issues.
301
302
```javascript { .api }
303
// Debugging techniques:
304
// 1. Use --json output to see detailed results
305
// 2. Check plugin installation with npm ls
306
// 3. Validate configuration format
307
// 4. Use --why for bundle analysis
308
// 5. Enable verbose logging in custom plugins
309
// 6. Check file paths and permissions
310
// 7. Test with minimal configuration first
311
```
312
313
**Debugging Commands:**
314
315
```bash
316
# Check installed plugins
317
npm ls @size-limit/
318
319
# Validate configuration with JSON output
320
size-limit --json
321
322
# Analyze bundle composition
323
size-limit --why
324
325
# Test with minimal config
326
echo '{"size-limit":[{"path":"dist/bundle.js","limit":"100kB"}]}' > .size-limit.json
327
size-limit
328
```
329
330
### Error Recovery Strategies
331
332
Strategies for recovering from common error conditions.
333
334
```javascript
335
// Graceful degradation example
336
async function runSizeLimitWithFallback(plugins, config) {
337
try {
338
return await sizeLimit(plugins, config);
339
} catch (error) {
340
if (error instanceof SizeLimitError) {
341
// Try with basic file plugin only
342
console.warn("Falling back to basic file measurement");
343
const filePlugin = await import("@size-limit/file");
344
return await sizeLimit([filePlugin.default], config);
345
}
346
throw error;
347
}
348
}
349
```