gulp

How to use gulp to organize the different js file in different html?


How to use gulp to organize the different js file in different html?
is the only way I can do is to define each page to gulp task ? Or gulp have a better way can detect file automatically?

This is my situation below.
I have two html 'index.html','content.html'

And my gulp file:

gulp.task('index_concat', function() {
    return gulp.src('./app/js/plugin_A.js')
        .pipe(concat('index.js'))
        .pipe(gulp.dest('./build/js/'));
});
gulp.task('content_concat', function() {
    return gulp.src('./app/js/plugin_B.js')
        .pipe(concat('content.js'))
        .pipe(gulp.dest('./build/js/'));
});

If I had 100 pages, the tasks were too big!

I think this is a stupid way to define each page, but I have no idea how to get better.


Solution

  • You could use some name convention for your plugins like pluginName_index.js and pluginName_content.js . So you be able to do something like that:

    function yourFunction(pluginName,targetName){
       return gulp.src('./app/js/'+pluginName)
          .pipe(concat(targetName))
          .pipe(gulp.dest('./build/js/'));
    }
    
    fs.readdirSync('.app/js/pluginFolder')
    .filter(function(fileName) {
        var fileNameParts = fileName.split('_');
        yourFunction(fileName,fileNameParts[1]);
    });