Minifier of js, css, html and img files with CLI and programmatic interfaces
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Intelligent format detection and minification that automatically identifies content type and applies the appropriate minifier for maximum compatibility.
Automatically detects content format and applies the most suitable minifier using fallback chain processing.
/**
* Automatically detects format and applies appropriate minifier
* @param data - Source code content to minify (any supported format)
* @param options - Configuration options for all minifier types
* @returns Promise resolving to minified content or original data if no minifier succeeds
*/
function minify.auto(data: string, options?: MinifyOptions): Promise<string>;
interface MinifyOptions {
js?: JSMinifyOptions;
css?: CSSMinifyOptions;
html?: HTMLMinifyOptions;
img?: ImageOptions;
}Usage Examples:
import { minify } from "minify";
// Auto-detect JavaScript
const jsCode = "function hello(world) { console.log(world); }";
const minifiedJS = await minify.auto(jsCode);
// Result: Minified JavaScript (detected and processed as JS)
// Auto-detect CSS
const cssCode = "body { color: red; margin: 0px; }";
const minifiedCSS = await minify.auto(cssCode, {
css: { type: 'clean-css' }
});
// Result: Minified CSS (detected and processed as CSS)
// Auto-detect HTML
const htmlCode = "<html><body><h1>Hello</h1></body></html>";
const minifiedHTML = await minify.auto(htmlCode);
// Result: Minified HTML (detected and processed as HTML)
// Unknown format fallback
const unknownData = "This is plain text content";
const result = await minify.auto(unknownData);
// Result: Original data unchanged (no compatible minifier found)The auto-detection uses a sequential fallback approach, trying minifiers in order:
const minifierChain = [
'js', // JavaScript minification (first attempt)
'css', // CSS minification (second attempt)
'html', // HTML minification (third attempt)
'img' // Image processing (final attempt)
];
interface DetectionProcess {
inputData: string; // Original content
currentMinifier: string; // Current minifier being tried
lastError: Error | null; // Error from previous attempt
result: string; // Final result (minified or original)
}Detection Examples:
// Clear JavaScript detection
const clearJS = `
const greeting = "Hello World";
function sayHello() {
console.log(greeting);
}
`;
const result1 = await minify.auto(clearJS);
// Detected as JavaScript, minified accordingly
// Ambiguous content (could be CSS or JS)
const ambiguous = "body { color: red }";
const result2 = await minify.auto(ambiguous);
// First tries JS (fails), then CSS (succeeds)
// Clear HTML detection
const clearHTML = "<!DOCTYPE html><html><head><title>Test</title></head></html>";
const result3 = await minify.auto(clearHTML);
// Detected as HTML after JS and CSS attempts failAuto-detection is designed to be fault-tolerant and never throw errors:
interface ErrorTolerance {
suppressErrors: boolean; // Always true - errors are caught
returnOriginal: boolean; // Return original data on failure
logErrors: boolean; // Errors are silently handled
}
const errorHandlingBehavior = {
onMinifierError: 'try-next', // Try next minifier in chain
onAllMinifiersFail: 'return-original', // Return input data unchanged
onValidationError: 'skip-minifier', // Skip to next in chain
};Error Handling Examples:
// Malformed JavaScript
const malformedJS = "function unclosed() { console.log('test';";
const result1 = await minify.auto(malformedJS);
// JS minifier fails → tries CSS → tries HTML → returns original
// Binary data
const binaryData = Buffer.from([0x89, 0x50, 0x4E, 0x47]).toString();
const result2 = await minify.auto(binaryData);
// All minifiers fail gracefully → returns original data
// Empty input
const empty = "";
const result3 = await minify.auto(empty);
// Handled gracefully → returns empty stringConfigure options for all possible minifiers since the format is unknown:
interface AutoDetectionOptions {
js?: {
type?: 'putout' | 'terser' | 'esbuild' | 'swc';
putout?: PutoutOptions;
terser?: TerserOptions;
esbuild?: ESBuildOptions;
swc?: SWCOptions;
};
css?: {
type?: 'lightningcss' | 'clean-css';
'clean-css'?: CleanCSSOptions;
};
html?: HTMLMinifierOptions;
img?: {
maxSize?: number;
};
}Configuration Examples:
// Comprehensive configuration for all formats
const fullConfig = {
js: {
type: 'terser',
terser: {
mangle: false,
compress: { drop_console: true }
}
},
css: {
type: 'clean-css',
'clean-css': { level: 2 }
},
html: {
removeComments: true,
collapseWhitespace: true,
minifyJS: false, // Don't double-minify embedded JS
minifyCSS: false // Don't double-minify embedded CSS
},
img: {
maxSize: 50000 // 50KB limit for image inlining
}
};
const result = await minify.auto(unknownContent, fullConfig);
// Format-specific configuration
const jsOptimized = await minify.auto(possibleJS, {
js: {
type: 'esbuild',
esbuild: { minifyIdentifiers: true }
}
// Other formats use defaults
});Perfect for situations where input format cannot be predetermined:
// User-uploaded content
const userContent = getUserUploadedContent();
const optimized = await minify.auto(userContent);
// Dynamic template processing
const templateContent = processTemplate(templateData);
const minified = await minify.auto(templateContent, {
html: { removeComments: false } // Preserve template comments
});
// API response optimization
const apiResponse = await fetch('/api/assets/content').then(r => r.text());
const compressed = await minify.auto(apiResponse);Ideal for processing mixed content collections:
const mixedAssets = [
"function test() { return true; }", // JavaScript
"body { margin: 0; padding: 10px; }", // CSS
"<div>Hello World</div>", // HTML fragment
"/* Unknown comment style */" // Ambiguous
];
const processedAssets = await Promise.all(
mixedAssets.map(asset => minify.auto(asset, {
js: { type: 'esbuild' },
css: { type: 'lightningcss' },
html: { collapseWhitespace: true }
}))
);Useful for build tools and development workflows:
// Build tool integration
async function optimizeAsset(filePath, content) {
// Don't need to determine file type - let auto-detection handle it
return await minify.auto(content, {
js: { type: 'terser' },
css: { type: 'clean-css' },
html: { minifyJS: true, minifyCSS: true }
});
}
// Editor plugin
async function minifySelection(selectedText, userPreferences) {
return await minify.auto(selectedText, userPreferences);
}Auto-detection involves trying multiple minifiers:
interface PerformanceConsiderations {
minifierAttempts: number; // 1-4 minifiers tried per input
errorHandlingCost: number; // Minimal - errors caught efficiently
memoryUsage: number; // Low - no format pre-analysis
cpuUsage: number; // Variable - depends on successful minifier
}
const performanceNotes = {
bestCase: 'First minifier succeeds (JS detection)',
worstCase: 'All minifiers fail, returns original',
averageCase: '2-3 minifier attempts before success',
recommendation: 'Use specific minifiers when format is known'
};// When format is known, use specific minifiers for better performance
const knownJS = await minify.js(jsContent); // Direct - fastest
const unknownContent = await minify.auto(content); // Auto-detect - flexible
// Batch processing optimization
const results = await Promise.all([
minify.auto(content1, sharedConfig),
minify.auto(content2, sharedConfig),
minify.auto(content3, sharedConfig)
]);Auto-detection has inherent limitations:
// Good: Use for truly unknown content
const userUpload = await minify.auto(unknownUserContent);
// Better: Use specific minifiers when possible
const knownCSS = await minify.css(cssContent);
// Best: Combine both approaches
async function smartMinify(content, detectedType = null) {
if (detectedType) {
return await minify[detectedType](content);
}
return await minify.auto(content);
}