javascriptnode.jsgulpgulp-concat

gulp-concat for each project using wildcard


I have N projects that has the same structure and all the projects are inside src path:

projectName/

├── index.html
├── anotherPage.html
└── assets/
        ├── css/
        │   └── {bunchofstyles}.css
        ├── imgs/
        │   └── {bunchofimages}.{someImageFormat}
        └──js/
            └── {bunchofjs}.js

I want to join the css files into one, same for the javascript files. Im using gulp for this with gulp-concat, for example, for the js I have something similar to this:

//this was made by memory, if its wrong dont pay attention to the minnor details
var gulp = require("gulp");
var concat = require("gulp-concat");

gulp.task("joinJSFiles", function(){
    gulp.src("./src/**/assets/js/*.js")
        .pipe(concat("script.js"))
        .gulp.dest("./dist")
})

But I have the following issues:

  1. concat joins all the files that are in the gulp.src, including of other projects
  2. concat deletes the structure of my project, saving the file into dist root instead of having the same structure
  3. Optional: I have two tasks that make the same thing but for different extension, one for js and another for css, can I have a single task to get this approach?

How can I solve this?


Solution

  • Following the suggestion that @Mark made, I made a gulp task that loops over each project but instead of gulp-foreach I used gulp-flatmap (I think its the same thing) and followed the following SO anwser https://stackoverflow.com/a/39933109/4637140

    So my gulp task looks like this:

    gulp.task('joinJSFiles', function () {
      return gulp.src('src/*')
         .pipe(flatmap(function(steam, dir){
            return gulp.src(dir.path + "/assets/js/*.js", {base:dir.path})
              .pipe(concat("script.js"))
              .pipe(gulp.dest("./dist/"+path.relative(dir.base, dir.path+"/assets/js")))
      }))
    });