简体   繁体   中英

How can I combine these two Gulp tasks into a single one?

Right now I have two tasks: templates and js . templates has to run first so that changes are be picked up by js . I want to combine these, eliminating the intermediate file, so that the task works like this:

  1. Compile and concatenate templates into a single chunk of JS
  2. Concatenate that chunk with the rest of my application's JS code
  3. Output the whole thing as a single file

How can I do this?

Here's my current code:

var gulp         = require('gulp');
var handlebars   = require('gulp-handlebars');
var concat       = require('gulp-concat');
var wrap         = require('gulp-wrap');
var declare      = require('gulp-declare');

// Compile Handlebars templates into JS
gulp.task('templates', function() {
  return gulp.src('./templates/*.hbs')
    .pipe(handlebars({
        handlebars: require('handlebars')
    }))
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
        namespace: 'templates',
        noRedeclare: true,
    }))
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('./js/'));
});

// Concatenate and minify application JS
gulp.task('js', function() {
  return gulp.src('./js/*.js')
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./dist/js'));

For me the easyest and cleaner way is to call one task after the other with

gulp.task('js', ['templates'], function(){
....

In this way the js task need the execution of templates task

Keeping the compilation and the final concat in 2 separate task it's not that bad for me.

Let me know if it's not a viable solution for you

EDIT

in one single task you can try to use merge-stream

and do

var merge = require('merge-stream');
gulp.task('templates', function() {
  var jsStream = gulp.src('./js/*.js')
   .pipe(concat('all.js'));
  var templateStream = gulp.src('./templates/*.hbs')
    .pipe(handlebars({
        handlebars: require('handlebars')
    }))
    .pipe(wrap('Handlebars.template(<%= contents %>)'))
    .pipe(declare({
        namespace: 'templates',
        noRedeclare: true,
    }))
    .pipe(concat('templates.js'));

    merge(jsStream, templateStream)
    .pipe(concat('app.js'))
    .pipe(gulp.dest('./dist/js'));
});

I've done it by heart without trying so my not work as intended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM