Converting Images to WebP with Node.js

02/08/2020 2 min read

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...😖

So, instead of adding another module to my project, I used a tiny node script for converting my images with 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: [
      //   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:

  <source srcset="someimage.webp" type="image/webp">
  <source srcset="someimage.jpg" type="image/jpeg"> 
  <img src="someimage.jpg" alt="An awesome image">