Skip to content

Instantly share code, notes, and snippets.

@kylemilloy
Last active August 15, 2017 17:14
Show Gist options
  • Save kylemilloy/420b8696d5efa4d6f170199cf9227e7d to your computer and use it in GitHub Desktop.
Save kylemilloy/420b8696d5efa4d6f170199cf9227e7d to your computer and use it in GitHub Desktop.
A batch PNG/JPG -> WEBP converter.
const fs = require('fs-extra');
const webp = require('webp-converter');
/**
* Return a list of files to be ignored by the CopyWebpackPlugin
*/
class FileList {
/**
* Init
* @param string folder the folder in which to find the files
* @param string prefix prefix to add to the reordered files
* @return {self} return an instance of the class
*/
constructor(folder, prefix) {
this.paths = [];
this.folder = folder ? folder : __dirname;
this.prefix = prefix;
return this;
}
readDir(folder) {
if (!folder) folder = this.folder;
let files = fs.readdirSync(folder);
files = files.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item));
files.forEach(item => {
// Path of item
let path = `${folder}/${item}`;
if (fs.lstatSync(path).isDirectory()) {
this.readDir(path);
}
else {
path = this.sliceFolder(path);
if (this.prefix) {
path = this.prefixFolder(path);
}
this.paths.push(path);
}
});
return this;
}
sliceFolder(path) {
return path.slice(this.folder.length + 1, path.length);
}
prefixFolder(path) {
return `${this.prefix}/${path}`;
}
}
// convert webp
const inPath = __dirname + '/resources/assets/img';
const outPath = __dirname + '/public/img';
let files = new FileList(inPath).readDir().paths;
for (let file of files) {
var convertable = /\.(jpe?g|png)$/i;
if (convertable.test(file)) {
const ext = /\.[^.$]+$/i;
const output = file.replace(ext, '.webp');
webp.cwebp(`${inPath}/${file}`, `${outPath}/${output}`, '-q 50', status => {});
}
}
@kylemilloy
Copy link
Author

I usually add this to my package.json as a command...run it with node webp-converter.js.

Just change the inPath/outPath where your assets are relatively located and it'll rename the files and replace the extensions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment