npm.io
2.0.0 • Published 2 months ago

postcss-encode-background-svgs

Licence
MIT
Version
2.0.0
Deps
0
Size
10 kB
Vulns
0
Weekly
0
Stars
9

PostCSS Encode Background SVGs

CI npm version

PostCSS plugin to encode background-image SVGs for cross browser compatibility.

The Problem

Background image SVGs are great but they don't render on IE unless encoded properly.

The Solution

Write your background as you usually would:

/* Input example */
background-image: url('data:image/svg+xml, <svg xmlns="http://www.w3.org/2000/svg"></svg>');

This encoder will then take your readable SVG and return a UTF-8 cross browser encoded solution like so:

/* Output example */
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E");

Requirements

  • Node.js >= 20
  • PostCSS 8 (peer dependency)

Installation

pnpm

pnpm add -D postcss postcss-encode-background-svgs

npm

npm install --save-dev postcss postcss-encode-background-svgs

Usage

In your postcss.config.js:

module.exports = {
    plugins: {
        'postcss-encode-background-svgs': {}
    }
};

Or via the API — the package ships both ESM and CommonJS builds with TypeScript types:

// ESM
import postcss from 'postcss';
import encodeBackgroundSVGs from 'postcss-encode-background-svgs';

postcss([encodeBackgroundSVGs()]);
// CommonJS
const postcss = require('postcss');
const encodeBackgroundSVGs = require('postcss-encode-background-svgs');

postcss([encodeBackgroundSVGs()]);

See the PostCSS docs for examples for your environment.

Once included in your environment, the plugin will search for any scss value with data:image/svg+xml.

Migrating from v1

Version 2 is a modernisation release — the encoding behaviour is unchanged:

  • PostCSS 8 is now a peer dependency (v1 bundled PostCSS 6); install postcss alongside the plugin
  • Node.js >= 20 is required
  • The plugin registers under the name postcss-encode-background-svgs (previously postcss-urlencode-background-svgs)

Credits

Big thanks for Vasi and Rob for their help with the Regex.

MIT Chris Boakes

Keywords