At a quick glance, the JavaScript function appears to attempt to minify inline JavaScript within an HTML file, but there are a few issues and potential improvements to consider:
-
Regex for Matching <script> Tags:
- The regex
/<script\b[^>]*>([\s\S]*?)<\/script>/gi is used to match <script> tags and their content. This seems appropriate for capturing inline scripts.
-
Checking for JavaScript Content:
- The function checks if the script content is non-empty (
jsContent.trim()) and either lacks a type attribute or has type="text/javascript". This is a good practice to avoid minifying non-JavaScript scripts (like type="text/html" or others).
-
Minification using UglifyJS:
- The function uses
UglifyJS.minify(jsContent) to minify the JavaScript content. This is correct if UglifyJS is properly imported and available.
-
Error Handling:
- The function checks for errors in the minification result (
!result.error) before replacing the original script content with the minified version. This is a good practice to avoid replacing content if minification fails.
-
Writing to Temporary File:
- The function writes the potentially modified content back to a temporary file and then processes it further with an external tool (
minhtml).
Potential Issues and Improvements
-
Importing UglifyJS:
-
Handling type Attribute More Robustly:
- The current check for the
type attribute could be improved. For example, it should handle cases where the type attribute is present but not set to text/javascript.
-
Avoiding Double Writes:
- The function writes to the temporary file twice. This could be optimized to write only once after all modifications are done.
-
Edge Cases:
- Consider edge cases where scripts might have unusual attributes or nested tags.
Here’s a slightly improved version addressing some of these points:
const UglifyJS = require('uglify-js');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
function processFile(content, config, ext, output, dest) {
if (config.outputMinifyHtml && ['.html', '.htm'].includes(ext)) {
const tempFile = path.join(output, 'temp_' + Date.now() + '_' + Math.floor(Math.random() * 1000) + '.html');
// Minify inline JS if enabled
let processedContent = content;
if (config.minifyJsInline) {
processedContent = content.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi, (match, jsContent) => {
// Skip non-JS script tags and empty content
if (jsContent.trim() &&
(!match.includes('type=') || match.includes('type="text/javascript"'))) {
const result = UglifyJS.minify(jsContent);
return !result.error ? match.replace(jsContent, result.code) : match;
}
return match;
});
}
fs.writeFileSync(tempFile, processedContent);
execSync(`"${config.minhtml}" ${config.outputMinifyHtmlOptions} --output "${dest}" "${tempFile}"`);
fs.unlinkSync(tempFile);
}
}
This version ensures that UglifyJS is imported and handles the type attribute more robustly.