Created
August 30, 2011 19:06
-
-
Save kirbysayshi/1181731 to your computer and use it in GitHub Desktop.
quick node script to inline a css stylesheet into html
This file contains 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
#!/usr/bin/env node | |
var fs = require('fs') | |
,jsdom = require('jsdom') | |
,cssom = require('cssom') | |
,request = require('request') | |
,style = fs.readFileSync('./styles.css', 'utf8') | |
,tpls = [ | |
'tpl_content/another_template.html' | |
,'tpl_content/another_template.html' | |
] | |
,outputDir = '_tpl_inlined' | |
,styles = cssom.parse( style ) | |
,jqueryStr; | |
function inlineAll(){ | |
tpls.forEach(function(el, i){ | |
jsdom.env({ | |
html: fs.readFileSync(el, 'utf8') | |
,src: [jqueryStr] | |
,done: function(errors, window){ | |
var i, j, rule, prop, val, inlined, outPath | |
for(i = 0; i < styles.cssRules.length; i++){ | |
rule = styles.cssRules[i] | |
for(j = 0; j < rule.style.length; j++){ | |
prop = rule.style[j]; | |
val = rule.style[prop]; | |
window.$( rule.selectorText ).css(prop, val); | |
} | |
} | |
inlined = window.$('body').html(); | |
// prevent crap like {include "header"} | |
inlined = inlined.replace(/\{(\S*)\s"(.*?)"\}/gi, function(substr, m1, m2, offset, s){ | |
//console.log(arguments); | |
return '{' + m1 + ' ' + '"' + m2 + '"}'; | |
}) | |
outPath = outputDir + '/' + el.split('/').pop(); | |
fs.writeFileSync(outPath, inlined) | |
console.log('inlined', outPath); | |
} | |
}) | |
}); | |
} | |
request('http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js', function(err, response, body){ | |
if (!err && response.statusCode == 200) { | |
jqueryStr = body; | |
inlineAll(); | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment