编写一款自定义修改html文件中的img、script、html hash后缀的简单插件
我们这篇文章将根据我们自己的一些项目需求,来编写一个本地gulp
插件,来满足我们的构建开发需求,主要需求就是在编译html
的同时,对html
文件中的静态资源引用添加随机hash
后缀
。
插件代码实现
index.js
var through = require("through2")
// 正则替换
function addSuffix(file_content_txt){
var re1 = /\s*src\s*=(\s*[\"\']{1}\s*)([^>]*)(\s*[^>]*[\"\']{1})/ig
var re2 = /\s*href\s*=(\s*[\"\']{1}\s*)([^>]*)(\s*[^>]*[\"\']{1})/ig
var str1 = file_content_txt.replace(re1, ($0, $1, $2, $3) => {
return ' '+$0.replace(/\s*/g, '').slice(0,-1)+'?version='+Math.floor(Math.random()*100000000000)+$1.replace(/\s*/g,'')+' '
})
var str2 = str1.replace(re2, ($0, $1, $2, $3) => {
return ' '+$0.replace(/\s*/g, '').slice(0,-1)+'?version='+Math.floor(Math.random()*100000000000)+$1.replace(/\s*/g,'')+' '
})
return str2
}
module.exports = function(suffix){
var stream = through.obj(function(file, encoding, callback){
// 如果file类型不是buffer 退出不做处理
if(!file.isBuffer()){
return callback();
}
// 获取文件中的内容 添加随机后缀
file_content_txt = file.contents.toString('utf-8')
// 将hash加到资源引用数据末尾
file.contents = Buffer.from(addSuffix(file_content_txt), 'utf-8')
// 确保文件会传给下一个插件
this.push(file);
// 告诉stream引擎,已经处理完成
callback();
});
return stream;
}
编译执行
cmd
C:\web\gulp\gulp_test>gulp
[11:41:23] Using gulpfile C:\web\gulp\gulp_test\gulpfile.js
[11:41:23] Starting 'default'...
[11:41:23] Starting 'clear'...
[11:41:23] Finished 'clear' after 12 ms
[11:41:23] Starting 'suffixs'...
[11:41:23] Finished 'suffixs' after 27 ms
[11:41:23] Finished 'default' after 43 ms
编辑 gulpfile.js
构建文件
gulpfile.js
let gulp = require("gulp");
let del = require('del')
let suffix = require('./modules/gulp-damiao-asset-suffix/index.js')
const clear = (done) => {
del.sync(['./dist/html/*','!./dist/newjs','./dist/newcss/*','./dist/newcss'])
done()
}
const suffixs = (done) =>{
gulp.src(['./html/home.html'])
.pipe(suffix()) //添加后缀
.pipe(gulp.dest('./dist/html/'))
done()
}
exports.default = gulp.series(clear, suffixs)
最终构建完成的效果
home.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>new html</title>
<script type="text/javascript" src="js/main.js?version=1095558455" ></script>
<script type="text/javascript" src="js/update.js?version=87344321883" ></script>
<link rel="stylesheet" type="text/css" href="css/style1.css?version=87834019051" >
<link rel="stylesheet" type="text/css" href="css/style2.css?version=89304556039" >
</head>
<body>
hello world !
<section class="section-box-1"></section>
<section class="section-box-2"></section>
<image src="./images/01.jpg?version=49854059852" />
<image src="./images/02.jpg?version=10506994079" />
</body>
</html>