Recently, I needed to convert some images to WebP format in a Nuxt.js project. Naturally, I searched for some Nuxt.js modules and found myself npm-installing for a while...😖
Eventually, I found imagemin ✌
First, let's install our dependencies:
npm install imagemin
npm install imagemin-webp
Now, let's create a webp.js file with this script:
const imagemin = require("imagemin");
const imageminWebp = require("imagemin-webp");
imagemin(["./assets/images/*.{jpg,png}"], {
destination: "./assets/images/webp/",
plugins: [
imageminWebp({
// quality: 90
// ,
// resize: {
// width: 1000,
// height: 0
// }
}),
],
}).then(() => {
console.log("Images Converted Successfully!!!");
});
Now, run the script with:
node webp.js
If you want to serve images in webp format or other partly supported formats you will probably want to include your images with the picture
tag for the best support:
<picture>
<source srcset="someimage.webp" type="image/webp">
<source srcset="someimage.jpg" type="image/jpeg">
<img src="someimage.jpg" alt="An awesome image">
</picture>