0
# Auto-Detection Minification
1
2
Intelligent format detection and minification that automatically identifies content type and applies the appropriate minifier for maximum compatibility.
3
4
## Capabilities
5
6
### Auto-Detection Minifier Function
7
8
Automatically detects content format and applies the most suitable minifier using fallback chain processing.
9
10
```javascript { .api }
11
/**
12
* Automatically detects format and applies appropriate minifier
13
* @param data - Source code content to minify (any supported format)
14
* @param options - Configuration options for all minifier types
15
* @returns Promise resolving to minified content or original data if no minifier succeeds
16
*/
17
function minify.auto(data: string, options?: MinifyOptions): Promise<string>;
18
19
interface MinifyOptions {
20
js?: JSMinifyOptions;
21
css?: CSSMinifyOptions;
22
html?: HTMLMinifyOptions;
23
img?: ImageOptions;
24
}
25
```
26
27
**Usage Examples:**
28
29
```javascript
30
import { minify } from "minify";
31
32
// Auto-detect JavaScript
33
const jsCode = "function hello(world) { console.log(world); }";
34
const minifiedJS = await minify.auto(jsCode);
35
// Result: Minified JavaScript (detected and processed as JS)
36
37
// Auto-detect CSS
38
const cssCode = "body { color: red; margin: 0px; }";
39
const minifiedCSS = await minify.auto(cssCode, {
40
css: { type: 'clean-css' }
41
});
42
// Result: Minified CSS (detected and processed as CSS)
43
44
// Auto-detect HTML
45
const htmlCode = "<html><body><h1>Hello</h1></body></html>";
46
const minifiedHTML = await minify.auto(htmlCode);
47
// Result: Minified HTML (detected and processed as HTML)
48
49
// Unknown format fallback
50
const unknownData = "This is plain text content";
51
const result = await minify.auto(unknownData);
52
// Result: Original data unchanged (no compatible minifier found)
53
```
54
55
## Detection Algorithm
56
57
### Fallback Chain Processing
58
59
The auto-detection uses a sequential fallback approach, trying minifiers in order:
60
61
```javascript { .api }
62
const minifierChain = [
63
'js', // JavaScript minification (first attempt)
64
'css', // CSS minification (second attempt)
65
'html', // HTML minification (third attempt)
66
'img' // Image processing (final attempt)
67
];
68
69
interface DetectionProcess {
70
inputData: string; // Original content
71
currentMinifier: string; // Current minifier being tried
72
lastError: Error | null; // Error from previous attempt
73
result: string; // Final result (minified or original)
74
}
75
```
76
77
### Detection Logic Flow
78
79
1. **JavaScript Detection**: Attempts to parse and minify as JavaScript
80
2. **CSS Detection**: If JS fails, tries CSS parsing and minification
81
3. **HTML Detection**: If CSS fails, attempts HTML minification
82
4. **Image Processing**: If HTML fails, tries image processing (requires file context)
83
5. **Fallback**: If all fail, returns original data unchanged
84
85
**Detection Examples:**
86
87
```javascript
88
// Clear JavaScript detection
89
const clearJS = `
90
const greeting = "Hello World";
91
function sayHello() {
92
console.log(greeting);
93
}
94
`;
95
const result1 = await minify.auto(clearJS);
96
// Detected as JavaScript, minified accordingly
97
98
// Ambiguous content (could be CSS or JS)
99
const ambiguous = "body { color: red }";
100
const result2 = await minify.auto(ambiguous);
101
// First tries JS (fails), then CSS (succeeds)
102
103
// Clear HTML detection
104
const clearHTML = "<!DOCTYPE html><html><head><title>Test</title></head></html>";
105
const result3 = await minify.auto(clearHTML);
106
// Detected as HTML after JS and CSS attempts fail
107
```
108
109
## Error Handling and Tolerance
110
111
### Graceful Failure Handling
112
113
Auto-detection is designed to be fault-tolerant and never throw errors:
114
115
```javascript { .api }
116
interface ErrorTolerance {
117
suppressErrors: boolean; // Always true - errors are caught
118
returnOriginal: boolean; // Return original data on failure
119
logErrors: boolean; // Errors are silently handled
120
}
121
122
const errorHandlingBehavior = {
123
onMinifierError: 'try-next', // Try next minifier in chain
124
onAllMinifiersFail: 'return-original', // Return input data unchanged
125
onValidationError: 'skip-minifier', // Skip to next in chain
126
};
127
```
128
129
**Error Handling Examples:**
130
131
```javascript
132
// Malformed JavaScript
133
const malformedJS = "function unclosed() { console.log('test';";
134
const result1 = await minify.auto(malformedJS);
135
// JS minifier fails → tries CSS → tries HTML → returns original
136
137
// Binary data
138
const binaryData = Buffer.from([0x89, 0x50, 0x4E, 0x47]).toString();
139
const result2 = await minify.auto(binaryData);
140
// All minifiers fail gracefully → returns original data
141
142
// Empty input
143
const empty = "";
144
const result3 = await minify.auto(empty);
145
// Handled gracefully → returns empty string
146
```
147
148
## Configuration Options
149
150
### Multi-Format Configuration
151
152
Configure options for all possible minifiers since the format is unknown:
153
154
```javascript { .api }
155
interface AutoDetectionOptions {
156
js?: {
157
type?: 'putout' | 'terser' | 'esbuild' | 'swc';
158
putout?: PutoutOptions;
159
terser?: TerserOptions;
160
esbuild?: ESBuildOptions;
161
swc?: SWCOptions;
162
};
163
css?: {
164
type?: 'lightningcss' | 'clean-css';
165
'clean-css'?: CleanCSSOptions;
166
};
167
html?: HTMLMinifierOptions;
168
img?: {
169
maxSize?: number;
170
};
171
}
172
```
173
174
**Configuration Examples:**
175
176
```javascript
177
// Comprehensive configuration for all formats
178
const fullConfig = {
179
js: {
180
type: 'terser',
181
terser: {
182
mangle: false,
183
compress: { drop_console: true }
184
}
185
},
186
css: {
187
type: 'clean-css',
188
'clean-css': { level: 2 }
189
},
190
html: {
191
removeComments: true,
192
collapseWhitespace: true,
193
minifyJS: false, // Don't double-minify embedded JS
194
minifyCSS: false // Don't double-minify embedded CSS
195
},
196
img: {
197
maxSize: 50000 // 50KB limit for image inlining
198
}
199
};
200
201
const result = await minify.auto(unknownContent, fullConfig);
202
203
// Format-specific configuration
204
const jsOptimized = await minify.auto(possibleJS, {
205
js: {
206
type: 'esbuild',
207
esbuild: { minifyIdentifiers: true }
208
}
209
// Other formats use defaults
210
});
211
```
212
213
## Use Cases and Applications
214
215
### Content Type Unknown Scenarios
216
217
Perfect for situations where input format cannot be predetermined:
218
219
```javascript
220
// User-uploaded content
221
const userContent = getUserUploadedContent();
222
const optimized = await minify.auto(userContent);
223
224
// Dynamic template processing
225
const templateContent = processTemplate(templateData);
226
const minified = await minify.auto(templateContent, {
227
html: { removeComments: false } // Preserve template comments
228
});
229
230
// API response optimization
231
const apiResponse = await fetch('/api/assets/content').then(r => r.text());
232
const compressed = await minify.auto(apiResponse);
233
```
234
235
### Batch Processing
236
237
Ideal for processing mixed content collections:
238
239
```javascript
240
const mixedAssets = [
241
"function test() { return true; }", // JavaScript
242
"body { margin: 0; padding: 10px; }", // CSS
243
"<div>Hello World</div>", // HTML fragment
244
"/* Unknown comment style */" // Ambiguous
245
];
246
247
const processedAssets = await Promise.all(
248
mixedAssets.map(asset => minify.auto(asset, {
249
js: { type: 'esbuild' },
250
css: { type: 'lightningcss' },
251
html: { collapseWhitespace: true }
252
}))
253
);
254
```
255
256
### Development Tools Integration
257
258
Useful for build tools and development workflows:
259
260
```javascript
261
// Build tool integration
262
async function optimizeAsset(filePath, content) {
263
// Don't need to determine file type - let auto-detection handle it
264
return await minify.auto(content, {
265
js: { type: 'terser' },
266
css: { type: 'clean-css' },
267
html: { minifyJS: true, minifyCSS: true }
268
});
269
}
270
271
// Editor plugin
272
async function minifySelection(selectedText, userPreferences) {
273
return await minify.auto(selectedText, userPreferences);
274
}
275
```
276
277
## Performance Characteristics
278
279
### Detection Overhead
280
281
Auto-detection involves trying multiple minifiers:
282
283
```javascript { .api }
284
interface PerformanceConsiderations {
285
minifierAttempts: number; // 1-4 minifiers tried per input
286
errorHandlingCost: number; // Minimal - errors caught efficiently
287
memoryUsage: number; // Low - no format pre-analysis
288
cpuUsage: number; // Variable - depends on successful minifier
289
}
290
291
const performanceNotes = {
292
bestCase: 'First minifier succeeds (JS detection)',
293
worstCase: 'All minifiers fail, returns original',
294
averageCase: '2-3 minifier attempts before success',
295
recommendation: 'Use specific minifiers when format is known'
296
};
297
```
298
299
### Optimization Strategies
300
301
```javascript
302
// When format is known, use specific minifiers for better performance
303
const knownJS = await minify.js(jsContent); // Direct - fastest
304
const unknownContent = await minify.auto(content); // Auto-detect - flexible
305
306
// Batch processing optimization
307
const results = await Promise.all([
308
minify.auto(content1, sharedConfig),
309
minify.auto(content2, sharedConfig),
310
minify.auto(content3, sharedConfig)
311
]);
312
```
313
314
## Limitations and Considerations
315
316
### Detection Accuracy
317
318
Auto-detection has inherent limitations:
319
320
- **Format Ambiguity**: Some content may be valid in multiple formats
321
- **Malformed Content**: Broken syntax may not be detected correctly
322
- **Mixed Content**: HTML with embedded JS/CSS is processed as HTML only
323
- **Comments Only**: Files containing only comments may not be detected
324
325
### Recommended Usage Patterns
326
327
```javascript
328
// Good: Use for truly unknown content
329
const userUpload = await minify.auto(unknownUserContent);
330
331
// Better: Use specific minifiers when possible
332
const knownCSS = await minify.css(cssContent);
333
334
// Best: Combine both approaches
335
async function smartMinify(content, detectedType = null) {
336
if (detectedType) {
337
return await minify[detectedType](content);
338
}
339
return await minify.auto(content);
340
}
341
```