public
Last active

quick node script to inline a css stylesheet into html

  • Download Gist
inliner.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#!/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 &quot;header&quot;}
inlined = inlined.replace(/\{(\S*)\s&quot;(.*?)&quot;\}/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();
}
})

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.