Skip to content

Instantly share code, notes, and snippets.

@zaim
Created March 5, 2013 13:09
Show Gist options
  • Save zaim/5090201 to your computer and use it in GitHub Desktop.
Save zaim/5090201 to your computer and use it in GitHub Desktop.
Grunt task to copy bower components to a static/public web directory. Organises based on file extension. Uses the "bower" cli, so no need to install the entire bower module.
module.exports = function (grunt) {
var path = require('path');
grunt.initConfig({
pkg : grunt.file.readJSON('package.json')
, bower : {
all : {
dest : 'static'
}
}
});
grunt.registerMultiTask('bower', 'Copy bower components', function () {
var done = this.async()
, dest = this.data.dest
, bower = {
cmd : 'bower'
, args : ['list', '--paths']
};
if (!grunt.file.isDir(dest)) {
grunt.verbose.writeln('Creating dest dir: ' + dest);
grunt.file.mkdir(dest);
}
grunt.util.spawn(bower, _copy);
function _copy (err, result, code) {
var components
, files
, name;
if (err || code) {
grunt.log.error("`bower list --paths' command failed to run:");
grunt.log.error(err.message || err);
grunt.log.error('Exit code: ' + code);
done(false);
return;
}
try {
components = JSON.parse(result)
} catch (e) {
grunt.log.error("Failed to parse `bower list --paths' output:");
grunt.log.error(e.message || e);
done(false);
return;
}
for (name in components) {
files = components[name];
files = grunt.util.kindOf(files) == 'string' ? [files] : files;
files.forEach(function (file) {
var basename = path.basename(file)
, extname = path.extname(file).slice(1)
, destname = path.join(dest, extname, basename);
grunt.file.copy(file, destname);
grunt.log.writeln(file + ' -> ' + destname.cyan);
});
}
done();
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment