Skip to content

Instantly share code, notes, and snippets.

@Akurganow
Created December 1, 2015 10:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Akurganow/61d531ab112833642a49 to your computer and use it in GitHub Desktop.
Save Akurganow/61d531ab112833642a49 to your computer and use it in GitHub Desktop.
PostCSS SVG Icons
path = require 'path'
fs = require 'fs'
fixedEncodeURIComponent = (str) ->
encodeURIComponent(str).replace(/[!'()*]/g, (c) ->
'%' + c.charCodeAt(0).toString(16)
)
injectColor = (svg, color) ->
svg.replace(/<svg[^>]*>/, "$&<style>*{fill:#{ color }}</style>")
svgPath = (decl, name) ->
imgdir = path.join(__dirname, '../..', 'images', 'icons')
name += '.svg'
path.join(imgdir, name)
inlineSvg = (decl, name, color, size = 'contain') ->
svg = fs.readFileSync(svgPath(decl, name)).toString('utf-8')
svg = injectColor(svg, color)
svg = fixedEncodeURIComponent(svg.replace(/'/gmi, '\\i'))
svg = "url(data:image/svg+xml;charset=US-ASCII,#{ svg })"
decl.cloneBefore({prop: 'background-image', value: svg})
decl.cloneBefore({prop: 'background-repeat', value: 'no-repeat'})
module.exports = (css) ->
css.walkDecls 'svg-icon', (decl) ->
declArr = decl.value.split(/\s+/)
name = declArr[0]
color = declArr[1]
size = declArr[2]
inlineSvg(decl, name, color, size)
decl.remove()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment