npmgulppackagevendors

npm - managing vendors for distribution


I am playing with Gulp.js & npm recently, it's great. However, I do not really get the idea of npm as a package manager for packages which will get pushed for dist.

Let's go with an example.

I want to download the latest jquery, bootstrap and font-awesome so I can include them into my project. I can simply download them from their websites and get the files to include. Another option seems to be a packet manager, i.e. NPM.

However, my node_modules directory is huge due to other packages such as gulp, and it's not nested at all. What would be the easiest way to move selected packages to another dir - for example src/vendors/

I was trying to achieve that by gulp task simply copying specified files from node_modules and moving them to a specified dir, nonetheless in the long run it's almost the same as manually copying files since I have to specify not only the input directory, but also the output directory for each single package.

My current solution:

gulp.task('vendors', function() {

    var jquery = gulp.src(vendors.src.jquery)
       .pipe(gulp.dest(vendors.dist.jquery));

    var bootstrap = gulp.src(vendors.src.bootstrap)
       .pipe(gulp.dest(vendors.dist.bootstrap));

    return merge(jquery, bootstrap);
});

vendors = {
    src: {
        jquery: 'node_modules/jquery/dist/**/*',
        bootstrap: 'node_modules/bootstrap/dist/**/*'
    },
    dist: {
        jquery: 'src/resources/vendors/jquery',
        bootstrap: 'src/resources/vendors/bootstrap'
    }
}

Is there an option to do it faster and/or better?


Solution

  • There's no need to explicitly specify the source and destination directory for each vendor library.

    Remember, gulp is just JavaScript. That means you can use loops, arrays and whatever else JavaScript has to offer.

    In your case you can simply maintain a list of vendor folder names, iterate over that list and construct a stream for each folder. Then use merge-stream to merge the streams:

    var gulp = require('gulp');
    var merge = require('merge-stream');
    
    var vendors = ['jquery/dist', 'bootstrap/dist'];
    
    gulp.task('vendors', function() {
      return merge(vendors.map(function(vendor) {
        return gulp.src('node_modules/' + vendor + '/**/*')
          .pipe(gulp.dest('src/resources/vendors/' + vendor.replace(/\/.*/, '')));
      }));
    });
    

    The only tricky part in the above is correctly figuring out the destination directory. We want everything in node_modules/jquery/dist to end up in src/resources/vendors/jquery and not in src/resources/vendors/jquery/dist, so we have to strip away everything after the first / using a regex.

    Now when you install a new library, you can just add it to the vendors array and run the task again.