Skip to content

Instantly share code, notes, and snippets.

@saionaro
Last active August 31, 2020 08:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saionaro/ecb055bba2f220c8c3c583250230ff5b to your computer and use it in GitHub Desktop.
Save saionaro/ecb055bba2f220c8c3c583250230ff5b to your computer and use it in GitHub Desktop.
Images optimization script
const compressImages = require("compress-images");
const VERBOSE = false;
const WEBP_QUALITY = 65;
const JPEG_QUALITY = 75;
const PNG_QUALITY_MIN = 40;
const PNG_QUALITY_MAX = 75;
const DEST_DIR = "./src/images/";
const SRC_DIR = "./src/images/original";
const webpify = (src, dest) => {
return new Promise((res, rej) => {
compressImages(
src,
dest,
{ compress_force: false, statistic: VERBOSE, autoupdate: true },
false,
{ jpg: { engine: "webp", command: ["-q", String(WEBP_QUALITY)] } },
{ png: { engine: "webp", command: ["-q", String(WEBP_QUALITY)] } },
{ svg: { engine: false, command: false } },
{ gif: { engine: false, command: false } },
(error, completed) => {
if (error) return rej(error);
if (completed) return res();
}
);
});
};
const optimize = (src, dest) => {
return new Promise((res, rej) => {
compressImages(
src,
dest,
{ compress_force: false, statistic: VERBOSE, autoupdate: true },
false,
{
jpg: { engine: "mozjpeg", command: ["-quality", String(JPEG_QUALITY)] },
},
{
png: {
engine: "pngquant",
command: [`--quality=${PNG_QUALITY_MIN}-${PNG_QUALITY_MAX}`],
},
},
{ svg: { engine: "svgo", command: "--multipass" } },
{ gif: { engine: false, command: false } },
(error, completed) => {
if (error) return rej(error);
if (completed) return res();
}
);
});
};
const start = async () => {
const webpGlob = `${SRC_DIR}/**/*.{jpg,JPG,jpeg,JPEG,png}`;
const optGlob = `${SRC_DIR}/**/*.{jpg,JPG,jpeg,JPEG,png,svg}`;
if (VERBOSE) console.log("Creating Webp...");
await webpify(webpGlob, DEST_DIR);
if (VERBOSE) console.log("Optimizaing...");
await optimize(optGlob, DEST_DIR);
};
start();
["compress-images@1.9.3:dev", "pngquant-bin:dev"]
{
"compress": "node ./scripts/compress.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment