roberto tomás
roberto tomás

Reputation: 4687

single gulp task for multiple sources and directories

I want to import all not all of my node_modules. One rule would be nice, rather than writing a new rule for each module.

Normally my task would look something like this:

gulp.task('node_modules', function () {
    return gulp.src('node_modules/**/*')
        .pipe(plumber({
            handleError: function (err) {
                console.log(err);
                this.emit('end');
            }
        }))
        .pipe(gulp.dest('build/node_modules'))
        .pipe(reload({ stream: true }))    
})    

But since I only want the ones that are useful to my project, and not, for example, useful to gulp, I need to specify them. However, if I specify multiple sources, they will all combine in the gulp.dest folder, so that won't work. On the other hand, if I abstract the call to gulp task (like the idea below), I think I may run into an issue with a lack of multiple return values.

I was thinking something like this:

function node_module(module) {
    gulp.task('node_module', function () {
        return gulp.src(`node_modules/${module}/**/*`)
            .pipe(plumber({
                handleError: function (err) {
                    console.log(err);
                    this.emit('end');
                }
            }))
            .pipe(gulp.dest(`build/node_modules/${module}`))
            .pipe(reload({ stream: true }))    
    })    
}
gulp.task('node_modules', function () {
    var rv
    ['event-emitter-es6', 'object-hash', 'urijs'].forEach(m => rv = node_module(m))
    return rv
})

Upvotes: 0

Views: 817

Answers (1)

Sven Schoenung
Sven Schoenung

Reputation: 30564

If you really know what you're doing, then this is not very difficult.

You can simply pass an array to gulp.src() that contains a glob for each of your modules. Then all you have to do is make sure everything ends up in the correct location in your destination directory.

The key thing you're missing is to use the base option to prevent your modules from being squished together in the same directory. (You can read more about what this option does in this question: how base option affects gulp.src & gulp.dest).

gulp.task('node_modules', function () {
  var modules = [ 'event-emitter-es6', 'object-hash', 'urijs' ];
  return gulp.src(modules.map(m => `node_modules/${m}/**/*`, {base:'node_modules'})
    .pipe(plumber({
        handleError: function (err) {
            console.log(err);
            this.emit('end');
        }
    }))
    .pipe(gulp.dest('build/node_modules'))
    .pipe(reload({ stream: true }))    
});

Also if the array of modules you want copied is identical to the dependencies in your package.json file you might as well just get the list from there instead of maintaining it manually:

var modules = Object.keys(require('./package.json').dependencies);

Upvotes: 2

Related Questions