Created
October 16, 2015 14:04
-
-
Save dmitriid/df22fb7bb6443bc9f997 to your computer and use it in GitHub Desktop.
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
/*** | |
* Compile *.styl files to css.css: | |
* node build_css.js | |
* | |
* Watch *.styl files and compile them to css.css: | |
* node build_css.js -w | |
*/ | |
var chokidar = require('chokidar'); | |
var stylus = require('stylus'); | |
var fs = require('fs'); | |
var clc = require('cli-color'); | |
var filesize = require('filesize'); | |
// make a new file watcher | |
var css = {}; | |
var inited = false; | |
var outFile = 'css/compiled/css.css'; | |
var opt = require('node-getopt').create([ | |
['w', '', 'watch the files'] | |
]) // create Getopt instance | |
.bindHelp() // bind option 'help' to default action | |
.parseSystem(); // parse command line | |
var watch = opt.options.w ? true : false; | |
var render_stats = function(){ | |
if(!inited) return; | |
var stats = fs.statSync(outFile); | |
var fileSizeInBytes = stats.size; | |
var kb = filesize(fileSizeInBytes, {base: 10, round: 2}); | |
console.log(clc.green(outFile), " ", clc.white(kb)); | |
if(!watch) process.exit(0); | |
}; | |
var do_render = function(){ | |
var out = Object.keys(css).map(function (key) { | |
return css[key]; | |
}).join('\n\n'); | |
fs.writeFileSync(outFile, out); | |
render_stats(); | |
}; | |
var render = function (filename) { | |
console.log('Rebuilding ' + filename); | |
var str = fs.readFileSync(filename); | |
stylus(str.toString()) | |
.set('filename', filename) | |
.include('css/css') | |
.render(function (err, rendered_css) { | |
if (err) { | |
console.log(clc.red('Could not parse file ', filename, err)); | |
if(!watch) process.exit(1); | |
return; | |
} | |
css[filename] = rendered_css; | |
do_render(); | |
}); | |
}; | |
// register for the `change` event | |
var watcher = chokidar.watch('css/css/*.styl'); | |
watcher | |
.on('add', render) | |
.on('change', render) | |
.on('unlink', function(filename){ | |
delete css[filename]; | |
do_render(); | |
}) | |
.on('error', function(error){ | |
console.log(clc.red('Could not parse file: ', error)); | |
if (!watch) process.exit(1); | |
}) | |
.on('ready', function(){ | |
inited = true; | |
render_stats(); | |
}); | |
setInterval(function () {}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment