mcr*_*n18 3 git gulp gulp-inject
我的目标是将最新的git commit附加到我的index.html文件中.
以下任务成功返回最新的git哈希(使用gulp-git):
var git = require('gulp-git');
gulp.task('hash', function() {
git.revParse({args:'--short HEAD'}, function (err, hash) {
return hash;
});
});
Run Code Online (Sandbox Code Playgroud)
以下任务构建我的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'))
});
Run Code Online (Sandbox Code Playgroud)
这成功地附加了一个字符串,index.html但是如何将hash任务的返回值注入html?
当然,您可以向哈希任务添加回调方法,以便将结果保存到变量中,以便在html任务中使用.html任务也应该将哈希任务作为依赖项,这样哈希就不会被定义.另外,你应该使用像gulp-cheerio这样的东西将哈希注入到输出中,这样你就不会在关闭的html标签之外附加哈希.
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'));
});
Run Code Online (Sandbox Code Playgroud)