Skip to content

Instantly share code, notes, and snippets.

@VanDalkvist
Created October 21, 2014 15:46
Show Gist options
  • Save VanDalkvist/3b74b85025a3ed386bd6 to your computer and use it in GitHub Desktop.
Save VanDalkvist/3b74b85025a3ed386bd6 to your computer and use it in GitHub Desktop.
var underscore = require('underscore');
var underscoreStr = require('underscore.string');
var concat = require('gulp-concat');
var gulp = require('gulp');
var exclude = ['lib1', 'lib2'];
gulp.task('bundle-libraries-auto', ['bower'], function(){
var bowerFile = require('./bower.json');
var bowerPackages = bowerFile.dependencies;
var bowerDir = './bower_components';
var packagesOrder = [];
var mainFiles = [];
// Function for adding package name into packagesOrder array in the right order
function addPackage(name){
// package info and dependencies
var info = require(bowerDir + '/' + name + '/bower.json');
var dependencies = info.dependencies;
// add dependencies by repeat the step
if(!!dependencies){
underscore.each(dependencies, function(value, key){
if(exclude.indexOf(key) === -1){
addPackage(key);
}
});
}
// and then add this package into the packagesOrder array if they are not exist yet
if(packagesOrder.indexOf(name) === -1){
packagesOrder.push(name);
}
}
// calculate the order of packages
underscore.each(bowerPackages, function(value, key){
if(exclude.indexOf(key) === -1){ // add to packagesOrder if it's not in exclude
addPackage(key);
}
});
// get the main files of packages base on the order
underscore.each(packagesOrder, function(bowerPackage){
var info = require(bowerDir + '/' + bowerPackage + '/bower.json');
var main = info.main;
var mainFile = main;
// get only the .js file if mainFile is an array
if(underscore.isArray(main)){
underscore.each(main, function(file){
if(underscoreStr.endsWith(file, '.js')){
mainFile = file;
}
});
}
// make the full path
mainFile = bowerDir + '/' + bowerPackage + '/' + mainFile;
// only add the main file if it's a js file
if(underscoreStr.endsWith(mainFile, '.js')){
mainFiles.push(mainFile);
}
});
// run the gulp stream
return gulp.src(mainFiles)
.pipe(concat('libs.js'))
.pipe(gulp.dest('./dist'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment