Skip to content

Commit

Permalink
Minify SVG #28
Browse files Browse the repository at this point in the history
  • Loading branch information
maltsev committed Apr 16, 2016
1 parent 5313027 commit 43ab0c9
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/htmlnano.es6
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const defaultOptions = {
minifyCss: {},
minifyJs: {},
minifyJson: {},
minifySvg: {},
custom: []
};

Expand Down
26 changes: 26 additions & 0 deletions lib/modules/minifySvg.es6
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import SVGO from 'svgo';
import posthtmlRender from 'posthtml-render';

/** Minify SVG with SVGO */
export default function minifySvg(tree, options, svgoOptions = {}) {
let promises = [];
let svgo = new SVGO(svgoOptions);

tree.match({tag: 'svg'}, node => {
let svgStr = posthtmlRender(node);
let promise = new Promise((resolve, reject) => {
svgo.optimize(svgStr, result => {
result ? resolve(result.data) : reject();
});
}).then(minifiedSvg => {
node.tag = false;
node.attrs = {};
node.content = minifiedSvg;
});
promises.push(promise);

return node;
});

return Promise.all(promises).then(() => tree);
}
21 changes: 21 additions & 0 deletions test/modules/minifySvg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { init } from '../htmlnano';

describe('minifySvg', () => {
const options = {minifySvg: {}};

it('should minify SVG inside <svg>', () => {
return init(
`<svg version="1.1" baseProfile="full" width="300" height="200" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="red" />
<circle cx="150" cy="100" r="80" fill="green" />
<text x="150" y="125" font-size="60" text-anchor="middle" fill="white">SVG</text>
</svg>`,

'<svg width="300" height="200" xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" fill="red"/><circle cx="150" cy="100" r="80" fill="green"/><text x="150" y="125" font-size="60" text-anchor="middle" fill="#fff">SVG</text></svg>',

options
);
});
});

0 comments on commit 43ab0c9

Please sign in to comment.