From e8988e0e4cbc7c00585704804bd03509ac9d1901 Mon Sep 17 00:00:00 2001 From: Amy Date: Thu, 14 Oct 2021 23:32:38 -0400 Subject: [PATCH] Refactor encoding constants --- scripts/optimize-images.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/scripts/optimize-images.ts b/scripts/optimize-images.ts index db82dab6..dadf9f98 100644 --- a/scripts/optimize-images.ts +++ b/scripts/optimize-images.ts @@ -19,12 +19,17 @@ const IMAGES_DESTINATION_DIRECTORY = "public/images"; void optimizeImages(); +const IMAGE_ENCODE_OPTIONS = { mozjpeg: {} }; +const GET_ENCODER_FROM_EXTENSION: { [imageExtension: string]: string } = { + jpg: "mozjpeg", + jpeg: "mozjpeg", +}; + export async function optimizeImages() { const imagePaths = await getFilePathsInDirectory(IMAGES_SOURCE_DIRECTORY); await fse.emptyDir(IMAGES_DESTINATION_DIRECTORY); const imagePool = new ImagePool(cpus().length); - const encodeOptions = { mozjpeg: {} }; await Promise.all( imagePaths.map(async (imagePath) => { @@ -33,9 +38,9 @@ export async function optimizeImages() { IMAGES_DESTINATION_DIRECTORY, imagePath ); - const fileExtension = imagePath.split(".").pop(); + const fileExtension = imagePath.split(".").pop() ?? ""; - if (!(fileExtension === "jpg" || fileExtension === "jpeg")) { + if (!GET_ENCODER_FROM_EXTENSION[fileExtension]) { await fse.copy(sourcePath, destinationPath); return; } @@ -44,10 +49,12 @@ export async function optimizeImages() { const ingestedImage = imagePool.ingestImage(rawImageFile); await ingestedImage.decoded; - await ingestedImage.encode(encodeOptions); + await ingestedImage.encode(IMAGE_ENCODE_OPTIONS); - const encodedImage = (await ingestedImage.encodedWith.mozjpeg).binary; - await fse.outputFile(destinationPath, encodedImage); + const encodedImage = await ingestedImage.encodedWith[ + GET_ENCODER_FROM_EXTENSION[fileExtension] + ]; + await fse.outputFile(destinationPath, encodedImage.binary); }) );