Gulp - Get return value of one task from another

2.7k views Asked by At

My goal is to append the latest git commit into my index.html file.

The following task successfully returns the latest git hash (using gulp-git):

var git = require('gulp-git');
gulp.task('hash', function() {
   git.revParse({args:'--short HEAD'}, function (err, hash) {
     return hash;
   });
});

The following task builds my HTML:

var inject = require('inject-string');
gulp.task('html', function () {
  return gulp.src('app/index.html')
    .pipe(inject.append('append git hash here!'))
    .pipe(gulp.dest('dist'))
});

This successfully appends a string into index.html but how do I inject the return value of the hash task into the html?

1

There are 1 answers

2
Ben On BEST ANSWER

Sure, you can add a callback method to your hash task so that you can save the result into a variable, to use in your html task. The html task should have the hash task as a dependency also, so that the hash is never undefined. In addition, you should probably use something like gulp-cheerio to inject the hash into the output, so that you're not appending the hash outside of the closing html tag.

var gulp = require('gulp'),
    git  = require('gulp-git'),
    cheerio = require('gulp-cheerio');

var gitHash;

gulp.task('hash', function(cb) {
  return git.revParse({args:'--short HEAD'}, function(err, hash) {
     gitHash = hash;
     cb();
   });
});

gulp.task('html', ['hash'], function() {
  return gulp.src('app/index.html')
    .pipe(cheerio(function($) {
        $('body').append('<p>' + gitHash + '</p>');
    }))
    .pipe(gulp.dest('dist'));
});