-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminify-html.js
71 lines (61 loc) · 2.21 KB
/
minify-html.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const fs = require('fs');
const path = require('path');
const { minify } = require('html-minifier-terser');
const distFolder = './dist';
function processDirectory(dir) {
fs.readdir(dir, (err, files) => {
if (err) {
console.error(`Error reading the ${dir} folder:`, err);
process.exit(1);
}
files.forEach((file) => {
const filePath = path.join(dir, file);
fs.stat(filePath, (err, stats) => {
if (err) {
console.error(`Error reading file stats for ${file}:`, err);
process.exit(1);
}
if (stats.isDirectory()) {
processDirectory(filePath);
} else if (path.extname(file) === '.html') {
minifyHtmlFile(filePath);
}
});
});
});
}
function minifyHtmlFile(inputPath) {
const outputPath = path.join(path.dirname(inputPath), path.basename(inputPath, '.html') + '.min.html');
fs.readFile(inputPath, 'utf8', (err, data) => {
if (err) {
console.error(`Error reading ${inputPath}:`, err);
process.exit(1);
}
minify(data, {
collapseWhitespace: true,
removeComments: true,
minifyJS: true,
minifyCSS: true,
})
.then((minifiedHtml) => {
fs.writeFile(outputPath, minifiedHtml, 'utf8', (err) => {
if (err) {
console.error(`Error writing minified ${inputPath}:`, err);
process.exit(1);
}
fs.rename(outputPath, inputPath, (err) => {
if (err) {
console.error(`Error replacing ${inputPath} with minified version:`, err);
process.exit(1);
}
console.log(`Successfully minified ${inputPath}`);
});
});
})
.catch((err) => {
console.error(`Error minifying ${inputPath}:`, err);
process.exit(1);
});
});
}
processDirectory(distFolder);