convert images to webp automatically

This commit is contained in:
Daniel Bulant 2021-08-25 18:04:31 +02:00
parent e49a836b1f
commit 1c629032d1
3 changed files with 54 additions and 1 deletions

48
imageMaker.js Normal file
View file

@ -0,0 +1,48 @@
import webp from "webp-converter";
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
async function convertFolder({ folder, production, base, out, ref }) {
const promises = [];
for(const file of await fs.readdir(folder)) {
const loc = path.join(folder, file);
const stat = await fs.stat(loc);
if(stat.isDirectory()) {
promises.push(convertFolder({ folder: loc, production, base, out }));
} else if([".png", ".jpg", ".jpeg"].includes(path.extname(loc))) {
var rel = loc.substr(base.length);
rel = rel.substr(0, rel.length - path.extname(rel).length);
const targetFile = path.join(out, rel + ".webp");
if(fsSync.existsSync(targetFile)) continue;
var target = path.join(out, rel);
console.log("target", target, path.basename(target));
var dir = target.substr(0, target.length - path.basename(target).length);
console.log("dir", dir);
if(!fsSync.existsSync(dir)) await fs.mkdir(dir, { recursive: true });
promises.push(webp.cwebp(loc, targetFile, "-q 80"));
} else {
ref.warn("Non-image file found:", loc);
}
}
return await Promise.all(promises);
}
export function makeImages({ folders, production }) {
return {
name: "image-maker",
generateBundle: async function makeImages() {
webp.grant_permission();
const base = path.join(__dirname, "images/png");
const out = path.join(__dirname, "public/sprite");
await fs.mkdir(out, { recursive: true });
const ref = this;
folders = folders.map(folder => path.join(base, folder));
await Promise.all(folders.map(folder => convertFolder({ folder, production, base, out, ref })));
}
};
};

View file

@ -26,6 +26,7 @@
"hammerjs": "^2.0.8",
"howler": "^2.2.1",
"phaser": "^3.54.0",
"sirv-cli": "^1.0.0"
"sirv-cli": "^1.0.0",
"webp-converter": "^2.3.3"
}
}

View file

@ -6,8 +6,11 @@ import { terser } from 'rollup-plugin-terser';
import css from 'rollup-plugin-css-only';
import workbox from 'rollup-plugin-workbox';
import replace from "@rollup/plugin-replace";
import { makeImages } from './imageMaker';
const production = !process.env.ROLLUP_WATCH;
// List of folders from images/png to convert to webp and save into public/sprite
const imageFolders = ["angels", "backgrounds", "button", "death", "levels"];
function serve() {
let server;
@ -59,6 +62,7 @@ export default [{
dedupe: ['svelte']
}),
commonjs(),
makeImages({ folders: imageFolders, production }),
// In dev mode, call `npm run start` once
// the bundle has been generated