Last active
September 27, 2022 11:33
-
-
Save erikyo/110088b656cce0d7d54886601a1f3a77 to your computer and use it in GitHub Desktop.
Optimizes the images stored into wordpress plugin/theme (encodes png to webp, jpg to mozjpeg and optimizes), add this alongside wp-scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Minifying images stored into ./assets/source-images saving them into the ./assets/dist | |
* | |
* Add to package.json: | |
* "imagemin": "^8.0.1", | |
* "imagemin-mozjpeg": "^10.0.0", | |
* "imagemin-svgo": "^10.0.1", | |
* "imagemin-webp": "^7.0.0", | |
* "graceful-fs": "^4.2.10" | |
* | |
* run the script with: | |
* "optimize-images": "node ./imagemin.mjs" | |
*/ | |
import imagemin from 'imagemin'; | |
import imageminWebp from 'imagemin-webp'; | |
import imageminSvgo from 'imagemin-svgo'; | |
import imageminMozjpeg from 'imagemin-mozjpeg'; | |
import { promises as fsPromises } from 'node:fs'; | |
import { promisify } from 'node:util'; | |
import path from 'node:path'; | |
import fs from 'graceful-fs'; | |
const writeFile = promisify(fs.writeFile); | |
// EDIT THIS PATHS | |
const srcdir = './assets/source-images'; | |
const distdir = './assets/images'; | |
imagemin([srcdir + '/**/*.{jpg,jpeg,png}'], { | |
plugins: [ | |
imageminWebp({quality: 82}) | |
] | |
}).then( (files) => | |
files.forEach(async (v) => { | |
let source = path.parse(v.sourcePath); | |
v.destinationPath = `${source.dir.replace(srcdir, distdir)}/${source.base}.webp`; | |
console.log(source.base +' -> ' + v.destinationPath); | |
await fsPromises.mkdir(path.dirname(v.destinationPath), { recursive: true }); | |
await writeFile(v.destinationPath, v.data); | |
}) | |
); | |
imagemin([srcdir + '/**/*.{jpg,jpeg,svg}'], { | |
plugins: [ | |
imageminSvgo({ | |
plugins: [{ | |
name: 'removeViewBox', | |
active: false | |
}] | |
}), | |
imageminMozjpeg() | |
] | |
}).then(files => files | |
.forEach(async v => { | |
let source = path.parse(v.sourcePath); | |
v.destinationPath = `${source.dir.replace(srcdir, distdir)}/${source.base}`; | |
console.log(source.base +' -> ' + v.destinationPath); | |
await fsPromises.mkdir(path.dirname(v.destinationPath), { recursive: true }); | |
await writeFile(v.destinationPath, v.data); | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment