/svg-style-bundler

A lightweight Javascript utility for inlining SVG styles

Primary LanguageJavaScript

SVG Style Bundler

A lightweight, zero-dependency Javascript utility that will convert all of an SVG element's computed styles to inline styles. Useful for converting SVGs to other image formats and otherwise porting them outside of their current context.

Inspired by the New York Times's excellent SVG Crowbar.

Installation

CDN

Include this script on your page

<script src="https://unpkg.com/svg-style-bundler"></script>

npm/yarn

npm install --save svg-style-bundler

then in your app

import styleBundler from 'svg-style-bundler';

or

const styleBundler = require('svg-style-bundler');

Usage

Pass in your SVG element using styleBundler.bundle(svgElement)

Note that this will alter the element, and may have unintended affects on appearance and responsiveness. I highly recommend performing this operation on a duplicate, like so:

const svg = document.querySelector('svg');
// Pass in true to also clone child nodes
const dupedSvg = svg.cloneNode(true);
// Insert the duplicate into the DOM
window.document.body.appendChild(dupedSvg);
styleBundler.bundle(dupedSvg);

Pairs nicely with Canvg.