Search code examples
javascriptgulpglob

How do I delete all files that match the basename in an array of globs?


I have an existing build task in my gulpfile, that transforms a collection of "source" files into "dist" files. I have an array of well-known filenames that tell my build task which files to operate on:

sourceFiles: [
    "./js/source/hoobly.js",
    "./js/source/hoo.js"
    ]

My build task produces the following files from this:

  • ./js/dist/hoobly.js
  • ./js/dist/hoobly.min.js
  • ./js/dist/hoobly.js.map
  • ./js/dist/hoobly.min.js.map
  • ./js/dist/hoo.js
  • ./js/dist/hoo.min.js
  • ./js/dist/hoo.js.map
  • ./js/dist/hoo.min.js.map

I now want to write a corresponding clean task that removes the files that get generated during my build task. Unfortunately I cannot just delete all the files in the ./js/dist/ directory, as this contains other files that are not generated by the build task in question, so I need to ensure that the files I delete match the "basename" of the orginal sourceFiles.

My question is: how do I go about using the sourceFiles array and "munging"* it so that I can end up calling something like:

gulp.src(sourceFiles)
    .pipe(munge()) // I don't know what to do here!!
    .pipe(del());  // does a `del ./js/dist/hoobly.*`
                   // and a  `del ./js/dist/hoo.*`

(*Technical term, "munge"...)

Can you point me in the right direction? I've looked at various NPM packages (vinyl-paths, gulp-map-files, gulp-glob, ...) and I'm just getting more and more lost.


Solution

  • I'd change globs before passing them to gulp.src:

    var sourceFiles = [
        "./js/source/hoobly.js",
        "./js/source/hoo.js"
        ];
        
    var filesToDelete = sourceFiles.map(f=>f.replace("/source/", "/dist/").replace(".js", ".*"));
    
    console.log(filesToDelete)

    and omit that munge step:

    gulp.src(filesToDelete).pipe(del())