rehypejs/rehype-minify

minifySVG (SVGO)

michael-ciniawsky opened this issue · 2 comments

Prototyped, untested :)

const visit = require('unist-util-visit')

const el = require('hast-util-is-element')
const to = require('hast-util-to-string')
const from = require('hast-util-from-string')

// $ = require('hast-utils')
// { el, to, from, etc., etc... } = require('hast-utils') 
// ? :)

const SVGO = require('svgo');
const svgo = new SVGO({/* options */}) 

module.exports = function minifySVG () {
  return (tree) => visit(tree, 'element', (node) => {
    if (el(node, 'svg')) {
      try {
        from(node, svgo.optimize(to(node), (result) => result.data))
      } catch (err) {
        console.log(err)
      }
    }     
  }
}

That’s really interesting! The fromString / toString don’t work here though (they just get text content, not tags), so we’ll have to use the compiler itself.

Ahh, i see, need to get more used to the API :)