Convert CSS Background SVG URL to Base64 with Node.js

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


Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.