Search code examples
gulpglob

Gulp src glob with multiple exclude


I'm very new to Gulp, trying to figure out how to exclude more than one file from a glob... for instance this works for a single file: return gulp.src(['assets/js/src/!(app)*.js'])

But is it possible / what would the syntax be for excluding multiple files? E.g. return gulp.src(['assets/js/src/!(app,test)*.js']) but obviously this doesn't work...

EDIT - I am later adding back in the files app.js & test.js so they are added at the end of the minified file.

e.g. (this works for a single file only:) return gulp.src(['assets/js/src/!(app)*.js', 'assets/js/src/app.js'])

I am looking for a solution to add multiple files back in at the end so I can control the order of the minified file. Also, it's important that I can use a glob to catch all files that will be added in future so I don't want to list them explicitly.


Solution

  • [You added some crucial information to your original post that completely changes the answer! You should edit your post with the new condition. So, with thanks to @dloeda glob negation:

    Now you might try gulp-filter

    const gulp = require('gulp');
    // const uglify = require('gulp-uglify');
    const filter = require('gulp-filter');
    
    gulp.task('default', () => {
       // Create filter instance inside task function
       const f = filter(['assets/js/src/*.js', '!assets/js/src/*{app,test}*.js'], {restore: true});
    
       return gulp.src('src/**/*.js')
        // Filter a subset of the files
        .pipe(f)
        // Run them through a plugin
        // .pipe(uglify())
        // Bring back the previously filtered out files (optional)
        .pipe(f.restore)
        .pipe(gulp.dest('dist'));
    });
    

    However, it is not clear to me from the gulp-filter documentation that the f.restore adds the filtered files at the end of the stream or back in their original location in the src stream. If you find that it doesn't put it at the end, let me know and it could be modified to do so by another method.

    Also see Contra's answer to adding to src if you are using gulp4.0 it is very easy to add to the src.

    Alternatively, gulp-add-src looks very promising and I just discovered it so you could try this alternative code:

    var addsrc = require('gulp-add-src');
    
    gulp.task('build', function () {
         // start with excluding app.js and test.js 
      return gulp.src(['assets/js/src/*.js', '!assets/js/src/*{app,test}*.js'])   
       // .pipe(whatever)                        
       .pipe(addsrc.append('assets/js/src/app.js')) // append app.js to the end of the stream 
       .pipe(uglify())               // we minify everything 
       .pipe(gulp.dest('dist'));     // and write to dist 
    });