-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathastro-integration-png-to-webp.mjs
More file actions
76 lines (64 loc) · 2.03 KB
/
astro-integration-png-to-webp.mjs
File metadata and controls
76 lines (64 loc) · 2.03 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
import sharp from 'sharp';
import { promises as fs } from 'node:fs';
import path from 'node:path';
export default function pngToWebpIntegration() {
return {
name: 'astro-integration-png-to-webp',
hooks: {
'astro:build:done': async ({ dir }) => {
const distDir = dir.pathname.replace(/^\/([a-zA-Z]):/, '$1:');
const pngFiles = await findPngFiles(distDir);
await Promise.all(
pngFiles.map(async (pngPath) => {
const webpPath = pngPath.replace(/\.png$/i, '.webp');
const image = sharp(pngPath);
const metadata = await image.metadata();
const hasAlpha = metadata.channels === 4 || metadata.channels === 2;
await image
.resize(512, 512, { fit: 'outside', withoutEnlargement: true })
.webp({ quality: 50, alphaQuality: hasAlpha ? 50 : undefined })
.toFile(webpPath);
await fs.unlink(pngPath);
}),
);
await updateReferences(distDir);
},
},
};
}
async function updateReferences(dir) {
const files = await findFiles(dir, ['.html', '.css', '.js']);
await Promise.all(
files.map(async (filePath) => {
let content = await fs.readFile(filePath, 'utf-8');
content = content.replace(/\.png/g, '.webp');
await fs.writeFile(filePath, content, 'utf-8');
}),
);
}
async function findFiles(dir, extensions) {
const files = [];
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await findFiles(fullPath, extensions)));
} else if (extensions.some((ext) => entry.name.toLowerCase().endsWith(ext))) {
files.push(fullPath);
}
}
return files;
}
async function findPngFiles(dir) {
const files = [];
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await findPngFiles(fullPath)));
} else if (entry.name.toLowerCase().endsWith('.png')) {
files.push(fullPath);
}
}
return files;
}