fix: assets optimization

This commit is contained in:
Torsten Dittmann
2024-08-21 15:25:14 +02:00
parent 9094b72e08
commit 54a4b52e09

View File

@@ -5,11 +5,20 @@ import { fileURLToPath } from 'url';
const __dirname = fileURLToPath(new URL('.', import.meta.url)); const __dirname = fileURLToPath(new URL('.', import.meta.url));
const root_dir = join(__dirname, '../static'); const root_dir = join(__dirname, '../static');
const exceptions = ['assets/'];
/**
* @type {{
* jpeg: sharp.JpegOptions,
* webp: sharp.WebpOptions,
* png: sharp.PngOptions,
* gif: sharp.GifOptions
* }}
*/
const config = { const config = {
jpeg: { quality: 80 }, jpeg: { quality: 80 },
webp: { quality: 80 }, webp: { quality: 80 },
png: { compressionLevel: 9 }, png: { compressionLevel: 9, quality: 80 },
gif: { quality: 80 } gif: { quality: 80 }
}; };
@@ -28,25 +37,34 @@ function* walk_directory(dir) {
} }
function is_image(file) { function is_image(file) {
const image_extensions = ["jpg", "jpeg", "png", "gif", "webp"]; const image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
const extension = file.split(".").pop().toLowerCase(); const extension = file.split('.').pop().toLowerCase();
return image_extensions.includes(extension); return image_extensions.includes(extension);
} }
function get_relative_path(file) { function get_relative_path(file) {
return relative(root_dir, file) return relative(root_dir, file);
} }
async function main() { async function main() {
for (const file of walk_directory(join(__dirname, '../static'))) { for (const file of walk_directory(join(__dirname, '../static'))) {
const relative_path = get_relative_path(file);
if (!is_image(file)) continue; if (!is_image(file)) continue;
console.log(get_relative_path(file)); if (exceptions.some((exception) => relative_path.startsWith(exception))) continue;
console.log(get_relative_path(relative_path));
const image = sharp(file); const image = sharp(file);
const size_before = (await image.toBuffer()).length; const size_before = (await image.toBuffer()).length;
const meta = await image.metadata(); const meta = await image.metadata();
const buffer = await image[meta.format](config[meta.format]).toBuffer(); const buffer = await image[meta.format](config[meta.format])
.resize({
width: 1280,
height: 1280,
fit: sharp.fit.inside
})
.toBuffer();
const size_after = buffer.length; const size_after = buffer.length;
if (size_after >= size_before) continue; if (size_after >= size_before) continue;