Search code examples
javascriptnode.jsbuild-processgulpgulp-concat

Gulp/Grunt: Concatenate only necessary JS files?


Wot I got

I have a gulpfile that produces app.min.js and libs.min.js; fairly selfexplanatory:

var dev = {
    libs: [
        'bower_components/angular/angular.min.js',
        'bower_components/angular-foundation/mm-foundation-tpls.min.js',
        'bower_components/underscore.string/dist/underscore.string.min.js'
    ]
};

var build = {
    js: 'public/js'
};

gulp.task('libs', function() {
    return gulp.src(dev.libs)
    .pipe(concat('libs.min.js'))
    .pipe(uglify({mangle: false}))
    .pipe(gulp.dest(build.js));
});

In this setup, whenever I add or remove a library, I have to manually add it to the dev.libs array (and in the right order, too), then restart Gulp to see the new lib file.

Wot I WANT

I want to be able to concat the js libs I use without having to specifically define them in (array) dev.libs. At the moment if I use return gulp.src('**/*.js'), I believe it will concat every single js file in bower_components, which'd obviously be ridiculous.

Question

Is there a way to automatically load and concat the libraries I need, without having to define them in a gulpfile?


Solution

  • For Bower, you can use the plugin main-bower-files that will parse the content of your bower.json and search for the main file(s) of each of your dependency, so you don't have to declare each lib.

    var bowerFiles = require('main-bower-files');
    

    You can then do :

    gulp.task('libs', function () {
      return gulp.src(bowerFiles())
        .pipe(concat('libs.min.js'))
        .pipe(uglify({mangle: false}))
        .pipe(gulp.dest(build.js));
    });