gulpgulp-concat

Gulp task to create page specific js files, concatenating common js files with page specific files


Assuming a directory structure like

I want to create distinct files that concatenate common + page1 and a separate file for common + page2.

Output to look something like

where script.js is each page's specific js concatenated to common.

I have something working on the sass side that creates the folders so really all I need to do is figure out how to get page specific files and drop them in a folder named for the original source file

return gulp.src(paths.styles.src)
    .pipe(sass().on('error', sass.logError))
    .pipe(postcss(processors))
     .pipe(rename(function(file) {
        file.dirname = file.basename;
        file.basename = 'style';
        file.extname = '.css';
    }))
    .pipe(gulp.dest(paths.styles.dest));

Solution

  • Try this for the js:

    const gulp = require("gulp");
    const glob = require("glob");
    const addSource = require("gulp-add-src");
    const concat = require("gulp-concat");
    const path = require("path");
    
    // get an array of files
    const files = glob.sync("./src/scripts/*.js");
    
    gulp.task('default', function () {
    
      files.forEach(function (file) {
    
        return gulp.src(file)
    
              // append or prepend here (prepend to put common.js first)
          .pipe(addSource.prepend('./src/scripts/_common/common.js'))
    
          .pipe(concat("script.js"))
    
          .pipe(gulp.dest("dist/" +  path.basename(file, '.js')));
      });
    });