如何寫一個能在gulp build pipe中任意更改src內容的函式

世有因果知因求果發表於2017-01-23

gulp在前端自動化構建中非常好用,有非常豐富的可以直接拿來使用的plugin,完成我們日常構建工作。

但是萬事沒有十全十美能夠完全滿足自己的需求,這時我們就要自己動手寫一個小的函式,用於在gulp stream pipeline中執行我們想要的動作,比如我有一個需求在build後將gulp-inject插入的assets url修改為laravel的一個helper以便識別不同的執行環境:如果是staging環境則不要上cdn方便除錯,如果是生產環境則將url修改為cdn的url,實現網站快速飛起來的夢想。怎們辦呢?

一個可行的偷懶方案是使用gulp-through2 plugin,不需要我們寫完整的plugin,而只需關注我們想要的功能:

https://meanstack.wordpress.com/2015/10/09/write-your-own-gulp-module-with-example-as-image-cache-buster-for-css/

function (file, enc, callback) {
var stringData = String(file.contents);
//loop for each supported images types
for (var i = 0; i < module.exports.supportedImages.length; i++) {
//add version of image
stringData = cssImageBusterForOneImageType(stringData, module.exports.supportedImages[i]);
}
var finalBinaryData = new Buffer(stringData, “binary”);
file.contents = finalBinaryData;
callback(null, file);
}
var jsOutputFile = “combined.js”;
var jsOutputFolder=”./dest/js”
var jsSrc=[“./src/js/**/*.js”];
gulp.task(‘jsconcat’, function () {
gulp.src(jsSrc)
.pipe(uglifyJs())
.pipe(concat(jsOutputFile, {newLine: ‘ ‘}))
.pipe(jshint())
.pipe(through.obj(imagebuster.jsImageBuster))
.pipe(gulp.dest(jsOutputFolder));
});

 

相關文章