Skip to content

Instantly share code, notes, and snippets.

@pyrocat101
Created May 16, 2013 09:12
Show Gist options
  • Save pyrocat101/5590474 to your computer and use it in GitHub Desktop.
Save pyrocat101/5590474 to your computer and use it in GitHub Desktop.
Compress CSS and convert linked images into data URIs. Suitable for HTML inlining and optimize HTTP requests.
embedImages = (cssPath) ->
imgRegex = /url\s?\(['"]?(.*?)(?=['"]?\))/gi
css = fs.readFileSync cssPath, 'utf-8'
while (match = imgRegex.exec css)
imgPath = path.join path.dirname(cssPath), match[1]
try
img = fs.readFileSync imgPath, 'base64'
ext = imgPath.substr imgPath.lastIndexOf('.') + 1
css = css.replace match[1], "data:image/#{ext};base64,#{img}"
catch e
console.error "Image not found (%s).", imgPath
return css
compressCSS = (css) ->
css
.replace(/\s+/g, ' ')
.replace(/:\s+/g, ':')
.replace(/\/\*.*?\*\//g, '')
.replace(/\} /g, '}')
.replace(/[ ]\{/g, '{')
.replace(/; /g, ';')
.replace(/\n+/g, '')
# Test
data = compressCSS embedImages("style.css")
fs.writeFile "style.min.css", data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment