利用gulp,当引入文件改动时,版本号自动更新~

时间:2023-03-08 18:37:07

gulp自动更新版本号

安装依赖

yarn add gulp-rev
yarn add gulp-rev-collector

本次依赖的版本号为:

"gulp": "^3.9.1"
"gulp-rev": "^8.0.0"
"gulp-rev-collector": "^1.1.1"

插件作用说明

gulp-rev

  • gulp-rev:Static asset revisioning by appending content hash to filenames unicorn.css → unicorn-d41d8cd98f.css
  • gulp-rev:静态资源更新,通过追加问价hash值到文件名之上,如:unicorn.css -> unicorn-d41d8cd98f.css

API


revFormat([options])

prefix

Type: string Default: "-"

Prefix appended to Hash.

(hash值的前缀)

suffix

Type: string Default: ""

Suffix appended to Hash.

(hash值的后缀)

lastExt

Type: boolean Default: false

Append formatted Hash just before last extension of a file.

(By default, gulp-rev and this plugin will append the formated Hash just before the first . of a filename)

If true, unicorn.ext1.ext2.css would become unicorn.ext1.ext2-d41d8cd98f.css

Note with default options, output is the same with gulp-rev: unicorn.css → unicorn-d41d8cd98f.css

gulp-rev-collector

  • Static asset revision data collector from manifests, generated from different streams, and replace their links in html template
  • 从manifests(清单)、各种流中收集静态资源信息,并在html之中替换该引用资源(用新的资源名)

使用方法:

  • We can use gulp-rev to cache-bust several assets and generate manifest files for them. Then using gulp-rev-collector we can collect data from several manifest files and replace links to assets in html templates.
  • 使用此插件必须基于gulp-rev生成的静态资源manifest,然后在html替换这些静态资源的引用。

实例分析

项目demo目录

- src
- css
- common.css
- img
- hsq.jpg
- js
- index.js
- index.html
- gulpfile.js

index.html代码
```html

Document

利用gulp自动添加版本号

利用gulp,当引入文件改动时,版本号自动更新~

```


gulpfile.js的配置如下
const gulp = require('gulp'),
rev = require('gulp-rev'),
revCollector = require('gulp-rev-collector'); gulp.task('css',function(){
return gulp.src('src/css/*.*')
.pipe(rev())
.pipe(gulp.dest('dist/css'))
.pipe(rev.manifest())
.pipe(gulp.dest('rev/css'))
}) gulp.task('js',function(){
return gulp.src("src/js/*.*")
.pipe(rev())
.pipe(gulp.dest("dist/js"))
.pipe(rev.manifest())
.pipe(gulp.dest('rev/js'))
}) gulp.task('rev',['css','js'],function(){
return gulp.src(['rev/**/*.json','src/*.html'])
.pipe(revCollector({
replaceReved: true
})).pipe(gulp.dest('dist'))
})

result:每次当文件变化的时候,那么该文件hash属性值就会变化,此时gulp-rev新形成新的json格式的manifest,当gulp-rev-collector读取json清单之后,就会在Html(任意视图文件)之中替换外部的链接。


新的Html文件为:
```html

Document

利用gulp自动添加版本号

利用gulp,当引入文件改动时,版本号自动更新~

```


但这样的结果并不是我们想要的,理由如下:
  • 增加了一些无语义的字符
  • 修改了本地的文件,导致文件的新旧不分,不知哪个是最终版本,需要手动删除(或许可以通过node删除,但无用功,因为新文件的hash值与原来不一样,当利用svn这样的工具时候,会需要全部上传,才能取消文件改动通知,不友好),然后再编译。

解决方案:不修改被引用资源的文件名,在模板之中,其请求链接之上改为 *.js?v=hash。

解决方案

手动修改这两个插件

gulp-rev:node_modules\gulp-rev\index.js

manifest[originalFile] = revisionedFile;/*( line 134 ) =>*/
manifest[originalFile] = originalFile + '?v=' + file.revHash;

rev-path:node_modules\rev-path\index.js

return filename + '-' + hash + ext;/*( line 10 )=>*/
return filename + ext;

gulp-rev-collector: node_modules\gulp-rev-collector\index.js (注意:gulp-rev-collector升级后会有变化)

if ( !_.isString(json[key]) || path.basename(json[key]).replace(new RegExp( opts.revSuffix ), '' ) !==  path.basename(key) ) {
isRev = 0;
}
/*(line 30)=>*/
if ( !_.isString(json[key]) || path.basename(json[key]).split('?')[0] !== path.basename(key) ) {
isRev = 0;
}
return pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\^\$\|\/\\]/g, "\\$&");
/*(line 50)=>*/
var rp = pattern.replace(/[\-\[\]\{\}\(\)\*\+\?\.\^\$\|\/\\]/g, "\\$&");
rp = pattern + "(\\?v=(\\d|[a-z]){8,10})*";
return rp;
patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) +                                        path.basename(key, path.extname(key)) )
+ opts.revSuffix
+ escPathPattern( path.extname(key) )
);
/*(line(90)=>)*/
patterns.push( escPathPattern( (path.dirname(key) === '.' ? '' : closeDirBySep(path.dirname(key)) ) + path.basename(key, path.extname(key)) )
+ opts.revSuffix
+ escPathPattern( path.extname(key) ) + "(\\?v=(\\d|[a-z]){8,10})*"
);

如此便达到目标了。

结果html如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="./css/common.css?v=2289731958">
</head>
<body>
<p> 利用gulp自动添加版本号 </p>
<img src="./img/hsq.jpg" alt="">
</body>
<script src="./js/index.js?v=8b50a3f85f"></script>
</html>

最后为方便使用,已经把修改好的文件发布到npm之上了;

到时候只需要下载下来直接替换个包的index.js文件即可;


yarn add gulp-rev-hu yarn add rev-path-hu yarn add gulp-rev-collector-hu

注意:下载我上传的文件之后,需要将官方版本的js文件进行替换,切记不要替换package,json文件