Created
May 16, 2013 09:12
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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