Convert CSS Background SVG URL to Base64 with Node.js

Last modified on December 20, 2019 1 min read

In this article, I’m going to share a simple way to convert CSS’s SVG URLs to Base64 with one click. According to Wikipedia, Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

Table of Contents

  1. Create Project & Install Dependencies
  2. Configure PostCSS
  3. Conversion

Step 1 : Create Project & Install Dependencies

Create a project folder and go to the project directory. Then run this command:

npm ini

We’ll use PostCSS for this conversion. We’re going to install 4 devDependencies. Run this command to install all:

npm i postcss postcss-svg postcss-preset-env cssnano -D

Here are the tasks of these dependencies:

  • postcss can lint your CSS, support variables and mixins, transpile future CSS syntax, inline images, and more.
  • postcss-svg lets you inline SVGs in CSS.
  • postcss-preset-env convert modern CSS into something browsers understand.
  • cssnano is a modular minifier, built on top of the PostCSS ecosystem.

Step 2 : Configure PostCSS

In the root folder of your project create a file called postcss.config.js and paste this code:

postcss.config.js
const postcssSVG = require('postcss-svg');
const postcssPresetEnv = require('postcss-preset-env');

module.exports = {
    plugins: [
        postcssSVG(),
        postcssPresetEnv(),
        require('cssnano')({
            preset: 'default',
        }),
    ],
};

If you don’t want to minify your converted CSS, then you need to remove cssnano from the config file.

Step 3 : Conversion

Our project is ready to use. Keep a CSS file in the root of your project and run this command to convert:

postcss demo.css > demo-converted.css

You can also store the converted file in another folder like this:

postcss demo.css > dist/demo.css

The tutorial is over. You can download this project from GitHub. Thank you. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Follow Buy me a coffeeBuy me a coffee

Leave a Reply

Your email address will not be published. Required fields are marked *