在gulp构建期间将git commit hash添加到javascript变量

the*_*ain 3 git fs node.js angularjs gulp

我正在使用gulp来构建我的angularjs应用程序,并希望以某种方式将最新的git commit hash注入我的角度应用程序中,以便我可以在调试生产问题时使用它.

即使只是将它作为全局变量注入我的index.html模板的情况也是如此.

任何人都可以推荐一个好的技术和插件来实现这一目标吗?

the*_*ain 7

我最终使用git-rev-sync和gulp-replace并将{{git}}放入我的index.html源文件中.

var git = require('git-rev-sync');

return gulp.src(pathConfig.src + 'index.html')
    .pipe($.replace('{{git}}', git.long()))
    .pipe(gulp.dest(pathConfig.dest + 'index.html'));
Run Code Online (Sandbox Code Playgroud)


Cod*_*ard 2

注入最新的 git 提交哈希值

您可以这样做:

git 将最新的提交哈希存储在.git/refs/heads/<branch name>.
使用以下代码读取文件的内容,然后将其放在您需要的位置

# load fs for reading /writing files
fs = require("fs"),

// define your task 
gulp.task('doSometing', function() {

  return gulp.src(dirs.src + '/templates/*.html')

    // read the  SHA-1 of the latest commit
    .pipe(fs.readFile("path/to/.git/refs/heads/<branch name>", 

          // Default encoding for fs is binary so we have to set it to UTF-8      
          "utf-8", 

          // Process the data you have read (SHA-1)
          function(err, _data) {
          //do something with your data
    })
   .pipe(gulp.dest('destination/path));
});
Run Code Online (Sandbox Code Playgroud)