Skip to content

Instantly share code, notes, and snippets.

@addyosmani
Last active December 14, 2015 21:59
Show Gist options
  • Save addyosmani/5154642 to your computer and use it in GitHub Desktop.
Save addyosmani/5154642 to your computer and use it in GitHub Desktop.
CSS unminify POC
javascript:(function () { 'use strict'; function unminCSS(code, tab) { var tabSize = 4; var space = ''; if (typeof tab === 'string'){ tab = /^\d+$/.test(tab) ? parseInt(tab,10) : tabSize; }; if (typeof tab === 'undefined'){ tab = tabSize; } if (tab < 0){ tab = tabSize; } code = code .split('\t').join(' ') .replace(/\s*{\s*/g, ' {\n\u00a0') .replace(/;\s*/g, ';\n\u00a0') .replace(/,\s*/g, ',\u00a0') .replace(/[ ]*}\s*/g, '}\n') .replace(/\}\s*(.+)/g, '}\n$1') .replace(/\n ([^:]+):\s*/g, '\n $1:&nbsp;') .replace(/([A-z0-9\)])}/g, '$1;\n}'); if (tab !== 4) { for (;tab != 0;tab--) { space += '\u00a0'; } code = code.replace(/\n /g, '\n'+space) } return code; } document.body.innerText = unminCSS(document.body.innerText); })();
// CSS unminifier for Pavel
// partly-based on the css cssunminifier npm module
// regex should be mostly portable if not done in
// the front-end
function unminCSS(code, tab) {
var tabSize = 4;
var space = '';
if (typeof tab === 'string'){
tab = /^\d+$/.test(tab) ? parseInt(tab,10) : tabSize;
}
if (typeof tab === 'undefined'){
tab = tabSize;
}
if (tab < 0){
tab = tabSize;
}
code = code
.split('\t').join(' ')
.replace(/\s*{\s*/g, ' {\n ')
.replace(/;\s*/g, ';\n ')
.replace(/,\s*/g, ', ')
.replace(/[ ]*}\s*/g, '}\n')
.replace(/\}\s*(.+)/g, '}\n$1')
.replace(/\n ([^:]+):\s*/g, '\n $1: ')
.replace(/([A-z0-9\)])}/g, '$1;\n}');
if (tab != 4) {
for (;tab != 0;tab--) { space += ' '; }
code = code.replace(/\n /g, '\n'+space);
}
return code;
}
// usage
var testCSS =".paul{font:normal 14px/20px helvetica,arial,sans-serif;color:red;}.pavel{font-weight:bold;-webkit-transform:translateZ(0);}.tim{color:blue;font-size:60px;}";
console.log(unminCSS(testCSS));
/*
.paul {
font: normal 14px/20px helvetica, arial;
color: red;
}
.pavel {
font-weight: bold;
-webkit-transform: translateZ(0);
}
.tim {
color: blue;
font-size: 60px;
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment