Do you need to convert a SVG file to a WEBP format? This article will walk you through how to do that.

We'll use Node.js as our coding language of choice and the Sharp NPM package to do most of the heavy lifting for us.

Table Of Contents

Install Sharp NPM Package

First, you need to install the NPM package. You can install it with either the npm or yarn command below:

      npm install sharp --save
      yarn add sharp

If everything went as planned, you should now have the Sharp NPM package installed.

Build A Hacker News Clone
Learn how to build and deploy a full-stack, production-ready application with React.js, Node.js, and MongoDB.
View Course

Convert SVG to WEBP

Now we're ready to start writing some code and converting an image! Make sure you have a SVG file in the root of your project directory that we can play around with.

Using the Sharp NPM package, here is the full code:

      const sharp = require("sharp")

        .then(function(info) {
        .catch(function(err) {

Let's break down each part of the code:

  1. First, we import the sharp NPM package and hold it in the sharp variable.
  2. Then, we use the sharp package to read our file.svg file, convert it to a WEBP and write the file to your directory with the .toFile() function.
  3. The sharp method is a promise and we use it to get the info for the file once it has been written to our directory.
  4. Last, we use .catch() method to catch and console.log() any errors.

When you run the code, you should get a similar output to this:

        format: 'webp',
        width: 2500,
        height: 527,
        channels: 4,
        premultiplied: false,
        size: 35600

And you should see the new WEBP file in your project directory.

There are also additional options you can pass to the .webp() method to alter the output image. These include the losslessness, quality level, and more. You can check them out in their documentation.

Build A Coding Blog From Scratch
A complete step-by-step guide to building and deploying a coding blog with a custom CMS using React.js, Node.js, MongoDB, & friends.
Free Course


Hopefully, this article helped you in your coding endeavors.

Thanks for reading and happy coding!