如何写一个能在gulp build pipe中任意更改src内容的函数

自定义gulp插件实践
本文介绍如何通过gulp-through2插件自定义gulp模块来修改构建过程中生成的文件内容,例如根据环境变化调整URL指向,确保不同环境下资源引用正确。

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));
});

 

转载于:https://www.cnblogs.com/kidsitcn/p/6344403.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值