加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.js 2.29 KB
一键复制 编辑 原始数据 按行查看 历史
LiuMY 提交于 2016-07-28 10:27 . package.json
'use strict';
var through = require('through2');
var assign = require('object-assign');
var gutil = require('gulp-util');
var pkg = require(process.cwd() + '/package.json');
// plugin name
const PLUGIN_NAME = 'gulp-html-version';
// default parameter
var defaults = {
paramName: 'v',
paramType: 'version',
suffix: ['css', 'js']
};
/**
* Short unique id generator
*/
var ShortId = function() {
var lastTime;
this.next = function() {
var d = new Date();
var thisTime = (d.getTime() - Date.UTC(d.getUTCFullYear(), 0, 1)) * 1000;
while (lastTime >= thisTime) {
thisTime++;
}
lastTime = thisTime;
return thisTime.toString(16);
};
};
function gulpHtmlVersion(options) {
// merge
var opts = assign(defaults, options);
var shortId = new ShortId();
// switch a parameter
switch (opts.paramType) {
case 'version':
opts.version = pkg.version;
break;
case 'guid':
opts.version = shortId.next();
break;
case 'timestamp':
opts.version = Date.now();
break;
}
// init regexp
var suffix = opts.suffix.join('|');
var regex = new RegExp('(\\s[\\w-]+=".+)(\\.' + suffix + ')(\\?[^&]+(?:&[^&]+)*)?(")', 'ig');
var stream = through.obj(function(file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
return cb();
}
var contents = file.contents.toString();
// replace
contents = contents.replace(regex, function(match, $1, $2, $3, $4) {
var version;
// append parameter
if ($3 != undefined) {
version = $3 + '&' + opts.paramName + '=' + opts.version;
} else {
version = '?' + opts.paramName + '=' + opts.version;
}
return $1 + $2 + version + $4;
});
file.contents = new Buffer(contents);
this.push(file);
cb();
});
return stream;
}
module.exports = gulpHtmlVersion;
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化