-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathcopy-html.js
More file actions
85 lines (72 loc) · 2.15 KB
/
copy-html.js
File metadata and controls
85 lines (72 loc) · 2.15 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import fs from 'fs';
import { globSync } from 'glob';
import { minify } from 'html-minifier-terser';
import path from 'path';
const SRC_FOLDER = path.resolve('./_site');
const DEST_FOLDER = path.resolve('./_deploy');
// -------------------------
// Utility functions
// -------------------------
/**
* Ensures the directory for a given file path exists.
* Creates parent directories recursively if missing.
* @param {string} filePath - Path to a file (not directory).
*/
function ensureDir(filePath) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
/**
* Gets all files matching the provided glob pattern.
* @param {string} globPattern - The glob pattern
* @returns {string[]} Array of matched file paths.
*/
function getAllFiles(globPattern) {
return globSync(globPattern);
}
// -------------------------
// HTML processing
// -------------------------
/**
* Minifies HTML content by removing whitespace, comments,
* and minifying embedded CSS/JS.
* @param {string} content - Raw HTML string.
* @returns {Promise<string>} Minified HTML content.
*/
function minifyHtml(content) {
return minify(content, {
collapseWhitespace: true,
minifyCSS: true,
minifyJS: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
});
}
/**
* Copies all `.html` files from the source folder, minifies them,
* and writes them to the destination folder while preserving structure.
* @returns {Promise<void>}
*/
async function copyAndMinifyHtmlFiles() {
const htmlFiles = getAllFiles(`${SRC_FOLDER}/**/*.html`);
for (const file of htmlFiles) {
const relativePath = path.relative(SRC_FOLDER, file);
const destPath = path.join(DEST_FOLDER, relativePath);
ensureDir(destPath);
const content = fs.readFileSync(file, 'utf-8');
const minified = await minifyHtml(content);
fs.writeFileSync(destPath, minified, 'utf-8');
}
}
// -------------------------
// Main execution
// -------------------------
/**
* Main entry point of the script.
* Runs HTML minification and (optionally) static asset copy.
* @returns {Promise<void>}
*/
(async function main() {
await copyAndMinifyHtmlFiles();
})();