-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
61 lines (54 loc) · 1.89 KB
/
index.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
import { promises as fs } from 'fs';
import path from 'path';
/**
* Astro integration to remove whitespace between HTML tags in build output
* @returns {import('astro').AstroIntegration}
*/
export default function removeTagWhitespace() {
return {
name: 'astro-remove-whitespace',
hooks: {
'astro:build:done': async ({ dir }) => {
console.log('🧹 Removing whitespace between html closing tags');
const removeWhitespace = (content) => {
return content.replace(/>\s+</g, '><');
};
// Process all HTML files
const processFile = async (filePath) => {
try {
const content = await fs.readFile(filePath, 'utf-8');
console.log(`Processing ${path.basename(filePath)}`);
const minified = removeWhitespace(content);
await fs.writeFile(filePath, minified, 'utf-8');
} catch (error) {
console.error(`Error processing ${filePath}:`, error);
}
};
// Walk through the dist directory
const walkDir = async (dirPath) => {
try {
const files = await fs.readdir(dirPath);
for (const file of files) {
const filePath = path.join(dirPath, file);
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
await walkDir(filePath);
} else if (file.endsWith('.html')) {
await processFile(filePath);
}
}
} catch (error) {
console.error(`Error walking directory ${dirPath}:`, error);
}
};
try {
let pathname = dir.pathname;
if (process.platform === 'win32') { pathname = pathname.replace('/', ''); }
await walkDir(pathname);
} catch (error) {
console.error('❌ Error in build hook:', error);
}
},
},
};
}